[英]How to convert ISO string format date time to next hour
我正在使用以下函數在 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 毫秒長,小時總是恰好 3.6e6 毫秒長,你可以只得到當前 UTC 時間值的剩余部分,如果它不為零(幾乎總是)加 1到 UTC 小時,然后將分秒和毫秒歸零,就像上面的ceilUTCHour函數一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.