时刻日期回溯到上个月

时间:2019-01-15 18:03:10

标签: javascript angular typescript momentjs

我有一个来自{} {1}}的日期时间。这是2018-09-01T00:00:00.000Z

我在程序中生成的另一个日期为frame.scandate。这只是2018-09。这些可能适用于任何年份/月份的组合,我仅举几个例子。

我的代码看起来像

scandate

这将使先前的 this.allStations.forEach(station => { station.frames.forEach(frame => { if(moment(frame.scandate).isSame(moment(scandate), 'month')){ total+=frame.framesTotal; } }) 与当前的frame.scandate相匹配。

此:

scandate

将输出以下内容:

scandate = '2018-09';\
frame.scandate = '2018-09-01T00:00:00.000Z';
console.log(moment(scandate).format('YYYY-MM'));
console.log(moment(frame.scandate).format('YYYY-MM'));

我通过以下方法解决了这个问题:

2018-09
2018-08

this.allStations.forEach(station => { station.frames.forEach(frame => { if(moment(frame.scandate).add(1, 'minute').isSame(moment(scandate), 'month')){ total+=frame.framesTotal; } }) 是此处的主要更改。

这是因为.add(1, 'minute')值具有frame.scandate时间值吗?任何解释将不胜感激。

1 个答案:

答案 0 :(得分:1)

There's probably something going on with the timezones.

This script, ran in Spain

var moment = require('moment'); // This is because I've tested it in a nodejs environment
var scandate = '2018-09';
var result = moment(scandate);
console.log(moment(result).format('YYYY-MM-DD'))

Outputs 2018-09-01


We could get around this by initializing frame.scandate like so:

frame.scandate = moment.utc('2018-09-01T00:00:00.000Z');

With moment.utc() instead of just moment() the output expectations are met.

相关问题