我正在使用momentJS来获取两个日期之间的差异。这是我的代码:
const createdAt = "2019-11-15 09:45:21"; // Sample data from mysql database
// Add time since created
const created = moment(createdAt);
const now = moment();
// get the difference between the moments
const diff = now.diff(created);
//express as a duration
const diffDuration = moment.duration(diff);
const days = diffDuration.days().toString().padStart(2, 0);
const hours = diffDuration.hours().toString().padStart(2, 0);
const minutes = diffDuration.minutes().toString().padStart(2, 0);
使用该代码,我可以正确地获取天,小时和分钟的差异。安装mysql的服务器位于菲律宾,并且createdAt
值由mysql自动生成。
现在,当我尝试更改PC的时区时,我得到了不正确的日期差。我得到负值。
我尝试做类似添加utc()
的事情:
const created = moment.utc(createdAt);
const now = moment.utc();
我仍然没有得到任何正确的值。我想念什么吗?是否有可能做到这一点?预先感谢。
答案 0 :(得分:1)
上述const S = require('sanctuary');
const source = {
foo: [{ r: 1 }, { r: 2 }, { r: 3 }],
bar: [{ r: 4 }, { r: 5 }, { r: 6 }],
}
const result =
S.pipe([
S.map(
prop => {
const nullable = S.maybeToNullable(S.value(prop)(source))
return nullable ? S.Just(nullable.map(val => {val['Section'] = prop; return val})) : S.Nothing
}
),
S.justs,
S.reduce(xs => x => [...xs, ...x])([])
])(['foo', 'bar', 'baz'])
时间不是 UTC格式,因此您需要通过添加/减去本地时间(即UTC时间)来更新值。最好将相关日期转换为UTC,然后从那里执行diff。
看看下面的解析和值选项:
createdAt
// utc time now
const utcTime = moment.utc();
console.log(utcTime.toString());
// time recorded at server
const philliTime = moment('2019-11-15 09:45:21', 'YYYY-MM-DD HH:mm:ss');
console.log(philliTime.toString());
// need to add 8 hours as philli is +8 hours
philliTime.add(8, 'h');
console.log(philliTime.toString());
// options using parseZone
const optionBPhilli = moment.parseZone('2019-11-15 09:45:21 +08:00', 'YYYY-MM-DD HH:mm:ss ZZ');
console.log(optionBPhilli.toString());
const optionBUTC = moment.parseZone('2019-11-15 09:45:21 +00:00', 'YYYY-MM-DD HH:mm:ss ZZ');
console.log(optionBUTC.toString());
console.log(optionBPhilli.diff(optionBUTC, 'h'))
有关解析字符串的更多信息,请检查moment docs并查看UTC parsing.