MomentJS 和天差
MomentJS and days difference
我的时区是 GMT+2。
当当地时间 '2020-05-21 01:00'
在 UTC 时区 (GMT+0)
中应该表示“2020-05-20 23:00”
所以天差应该说:1
此代码不会给出该结果。有人知道为什么吗?
编辑:简单地说:星期六凌晨 1 点在我这里是星期五晚上 11 点(协调世界时)。所以应该有 1 天的差异。这是实时代码示例
https://stackblitz.com/edit/moment-js-playground-vteexd?embed=1&file=index.ts
在内部,它们是同一日期。为了证明这一点,尝试比较它们的时间戳 now.format('X')
=== utc.format('X')
.
作为解决方案,我建议使用 moment durations 来测量时间差,并使用 .days()
来获得所需的值。
This could be of help.
这里我将给出我自己的问题的解决方案:
import moment from "moment-timezone";
//test for GMT+1
var now = moment().startOf("day").add(1, "hours");
console.log(now.format(), " now", now.format('dddd'));
let res= GetDayOffsetUTC(now);
console.log("Day diff: ", res);
// Get DAY difference between local and UTC time
// Responses:
// -1 : your local time is 1 day ahead of UTC
// 1 : your local time is 1 day after UTC
// 0 : your local time is same day as UTC
function GetDayOffsetUTC(date) {
const utcOffset = date.utcOffset();
const utc = date.clone().add(-utcOffset, "minutes");
const dayDiff = utc.startOf("day").diff(date.startOf("day"), "days");
return dayDiff;
}
我的时区是 GMT+2。
当当地时间 '2020-05-21 01:00'
在 UTC 时区 (GMT+0)
所以天差应该说:1
此代码不会给出该结果。有人知道为什么吗?
编辑:简单地说:星期六凌晨 1 点在我这里是星期五晚上 11 点(协调世界时)。所以应该有 1 天的差异。这是实时代码示例
https://stackblitz.com/edit/moment-js-playground-vteexd?embed=1&file=index.ts
在内部,它们是同一日期。为了证明这一点,尝试比较它们的时间戳 now.format('X')
=== utc.format('X')
.
作为解决方案,我建议使用 moment durations 来测量时间差,并使用 .days()
来获得所需的值。
This could be of help.
这里我将给出我自己的问题的解决方案:
import moment from "moment-timezone";
//test for GMT+1
var now = moment().startOf("day").add(1, "hours");
console.log(now.format(), " now", now.format('dddd'));
let res= GetDayOffsetUTC(now);
console.log("Day diff: ", res);
// Get DAY difference between local and UTC time
// Responses:
// -1 : your local time is 1 day ahead of UTC
// 1 : your local time is 1 day after UTC
// 0 : your local time is same day as UTC
function GetDayOffsetUTC(date) {
const utcOffset = date.utcOffset();
const utc = date.clone().add(-utcOffset, "minutes");
const dayDiff = utc.startOf("day").diff(date.startOf("day"), "days");
return dayDiff;
}