如何将ISO字符串格式的日期时间转换为下一个小时



我使用以下函数来转换RFC3339中的日期。我想把它转换成上限

谁能帮助我,我如何将其转换为上限?

const date = new Date();
// RFC 3339 format
const targetTime = date.toISOString();

当前输出为:

2022-12-20T05:26:12.968Z

预期输出应为

2022-12-20T06:00:00Z

看这个答案,非常相似,但你可以用Math.ceil代替Math.round,以便按你想要的方式进行四舍五入,此外,你需要得到小时完成的百分比(假设你不想精确四舍五入小时)。

const milliSecondsInHour = 60*60*1000;
const roundDateToNextHour = (date: Date) => {
const percentHourComplete = (x.getTime() % milliSecondsInHour) / milliSecondsInHour;
date.setHours(date.getHours() + Math.ceil(percentHourComplete));
date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
return date;
}

如果目的是下一个完整的UTC小时,测试UTC分钟,秒或毫秒是否大于零。如果其中任何一个是,则增加小时并将其他值置零,例如:

// If the provided date is not exactly on the UTC hour, 
// return a date that is the next full UTC hour after
// the provided date.
function toFullUTCHour(date) {
let d = new Date(+date);
d.setUTCHours(d.getUTCHours() + (d.getUTCMinutes() || d.getUTCSeconds() || d.getUTCMilliseconds? 1 : 0), 0,0,0);
return d;
}
let d = new Date()
console.log(d.toISOString() + 'n' +
toFullUTCHour(d).toISOString());

// Simplified version, only works in general for UTC hour
function ceilUTCHour(date = new Date()) {
let d = new Date(+date);
d.setHours(d.getHours() + (d%3.6e6? 1 : 0), 0, 0, 0);
return d;
}
console.log(ceilUTCHour(d).toISOString());

因为,在ECMAScript中,UTC天总是正好8.64e7 ms长,小时总是正好3.6e6 ms长,你可以只得到当前UTC时间值的剩余部分,如果它不是零(几乎总是),在UTC小时上加1,那么就像上面的ceilUTCHour函数一样,分、秒和毫秒都为零。

最新更新