这个JS时间码可以用吗?我可以让它变得更好吗?
我会在周六下午 6 点到周日凌晨 4 点之间显示一条消息。上次我不得不这样做时,它不起作用,因为我在将其更改为纽约时间时没有考虑到 UTC 时间为负数。
我的数学计算正确(在适当的时间显示)?我应该将 UTC 转换代码放入其自己的函数中吗?这是你见过的最糟糕的 js 吗?
-- 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
}
});
I'm displaying a message between Saturday at 6pm and Sunday 4am. 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.
I am doing the math right (displaying at the appropriate times)?Should I put the UTC conversion code into its own function? Is this the worst js you've ever seen?
-- jquery is called --
$(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
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么你还需要 UTC 的东西?只需使用当地时间:
您也可以稍微清理一下条件:
Why do you even need that UTC stuff? Just work with local time:
And you can clean up that conditional a bit too:
这应该可以得到服务器的时间:
在服务器偏移量中使用“5”;这是时间。它可能需要是-5;我不太确定。
而且,这将打破每个夏令时。您必须以某种方式检测到这一点并修改 serverOffset。
This should get you your server's time:
Play around with that "5" in the server offset; it's the hours. It may need to be a -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.