[英]Will this JS time code work? Can I make it better?
I'm displaying a message between Saturday at 6pm and Sunday 4am. 我在星期六下午6点至星期日凌晨4点之间显示一条消息。 The last time I had to do this it didn't work because I didn't take into account UTC time going negative when changing it to NYC time. 我最后一次这样做是不行的,因为我没有考虑将UTC时间改为NYC时间的时间。
I am doing the math right (displaying at the appropriate times)?Should I put the UTC conversion code into its own function? 我正在做正确的数学运算(在适当的时间显示)?我应该将UTC转换代码放入自己的函数中吗? Is this the worst js you've ever seen? 这是你见过的最糟糕的js吗?
-- jquery is called -- - jquery被称为 -
$(document).ready(function() {
var dayTime = new Date();
var day = dayTime.getUTCDay();
var hour = dayTime.getUTCHours();
//alert(day.toString()+" "+hour.toString());
if (hour >= 5){
hour = hour-5;
}
else{
hour = hour+19;
if(day > 0){
day--;
}
else{
day = 6;
}
}
//alert(day.toString()+" "+hour.toString());
if ((day == 6 && hour >= 18) || (day == 0 && hour < 4)){
}
else{
$('#warning').hide(); //Want this message to show if js is disabled as well
}
});
Why do you even need that UTC stuff? 为什么您甚至需要UTC的东西? Just work with local time: 只需与当地时间合作:
var day = dayTime.getDay();
var hour = dayTime.getHours();
And you can clean up that conditional a bit too: 您也可以清理一下该条件:
if (!(day == 6 && hour >= 18) && !(day == 0 && hour < 4)) {
$('#warning').hide();
}
This should get you your server's time: 这应该可以让你获得服务器的时间:
var dayTime = new Date();
localOffset = dayTime.getTimezoneOffset() * 60000;
serverOffset = 5 * 60 * 60000;
dayTime = new Date(dayTime.getTime() + (localOffset - serverOffset));
Play around with that "5" in the server offset; 在服务器偏移量中使用“5”; it's the hours. 时间到了 It may need to be a -5; 它可能需要为-5; I'm not really sure. 我不太确定。
Also, that's going to break every daylight savings. 此外,这将打破每一个夏令时。 You'll have to detect that somehow and modify serverOffset. 你必须以某种方式检测到并修改serverOffset。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.