如何在javascript日期添加1 UTC时间?

时间:2017-10-10 16:06:41

标签: javascript date datetime utc iso

使用javascript,如何获取非UTC日期,添加1 UTC时间,零时间(s),然后将其转换为ISO字符串?

new Date().toISOString()
  

2017-10-10T16:00:49.915Z

所需的UTC日期字符串

  

2017-10-11T00:00:00.000Z

1 个答案:

答案 0 :(得分:2)

下面我以毫秒为单位获取日期,以毫秒为单位添加1天。 然后,我以毫秒为单位除以一天,截断,然后再以天为单位,以毫秒为单位。



var d = new Date('2017-10-10T16:00:49.915Z');

function nextDayUTC(d) {
  var aDay = 1440 * 60 * 1000;
  var d2 = new Date( Math.trunc((d.getTime() + aDay)/aDay)*aDay);
  return d2;
}

function nextDayLocal(d) {
  //basically set to start of the day
  //add 36 hrs, this pretty much ensures next day
  //add then reset the hours back to 0
  var hr36 = 36 * 60 * 60 * 1000;
  var d2 = new Date(d);
  d2.setHours(0,0,0,0); 
  d2.setTime(d2.getTime() + hr36);
  d2.setHours(0,0,0,0);
  return d2;
}

console.log(d)
console.log("Next Day UTC");
console.log(nextDayUTC(d).toISOString());
console.log("Next Day Local");
console.log(nextDayLocal(d).toString());