微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

一年中的某天是否未在JavaScript中更新?

如何解决一年中的某天是否未在JavaScript中更新?

我有JavaScript代码可以计算一年中的某天(例如1月1日为1,10月30日为304):

var Now = new Date();

//leap year rules:
//  The year must be evenly divisible by 4;
//  If the year can also be evenly divided by 100,it is not a leap year
//  Unless the year is also evenly divisible by 400. Then it is a leap year.

if(Now.getUTCFullYear() % 4 == 0){
  //if the year is a leap year:
  if(Now.getUTCFullYear() % 100 != 0){
    var day = Math.ceil((Now - new Date(Now.getFullYear(),1)) / 86400000);
    document.getElementById('dayOfYear').innerHTML = day;
  }
  else if(Now.getUTCFullYear() % 100 == 0 && Now.getUTCFullYear() % 400 == 0){
    var day = Math.ceil((Now - new Date(Now.getFullYear(),1)) / 86400000);
    document.getElementById('dayOfYear').innerHTML = day;
  }
  else{
    var day = Math.ceil((Now - new Date(Now.getFullYear(),0)) / 86400000);
    document.getElementById('dayOfYear').innerHTML = day;
  }
  
}
else{
  //if the year is NOT a leap year
  var day = Math.ceil((Now - new Date(Now.getFullYear(),0)) / 86400000);
  document.getElementById('dayOfYear').innerHTML = day;
}

由于它是一个时钟应用程序,因此代码每秒刷新一次。但是,当时钟在第二天第二天00:00:00时,直到几小时之后才更新“一年中的一天”。可能是什么原因造成的?

谢谢!

解决方法

您正在使用本地值创建日期,但要计算UTC天数,以便它在UTC午夜而不是本地午夜计时。而且,该算法过于复杂。只需将UTC用于所有内容,例如

function getDayOfYear(d = new Date()) {
  // Start of year
  let yearStart = Date.UTC(d.getFullYear(),1);
  // Get difference to now / ms in one day
  return Math.floor(((Date.UTC(d.getFullYear(),d.getMonth(),d.getDate()) - yearStart)) / 8.64e7) + 1;
}

[new Date(2020,1),// 1 Jan 2020 
 new Date(),// today
 new Date(2020,11,31) // 31 Dec 2020
].forEach(d => console.log(d.toDateString() + ' is day ' + getDayOfYear(d)));

PS (Date.UTC(d.getFullYear(),d.getDate())也可以是(+d + d.getTimezoneOffset() * 6e4),它稍短一些,但可读性较低。

要在UTC午夜打勾:

function getUTCDayOfYear(d = new Date()) {
  // Start of year
  let yearStart = Date.UTC(d.getUTCFullYear(),1);
  // Get difference to now / ms in one day
  return Math.floor(((Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()) - yearStart)) / 8.64e7) + 1;
}

[new Date(Date.UTC(2020,1)),// 1 Jan 2020 UTC
 new Date(Date.UTC(2020,31)) // 31 Dec 2020 UTC
].forEach(d => console.log(d.toString() + ' is on UTC day ' + getUTCDayOfYear(d)));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。