我使用 moment
获取前一天,如下所示:
var start_time = moment().tz("America/Los_Angeles").subtract(1, 'day').format('YYYY/MM/DD-00:00:00');
输出如下:
2015/01/29-00:00:00
现在我想使用 start_time
执行以下操作:
2015/01/29-01:00:00
2015/01/29-02:00:00
2015/01/29-03:00:00
2015/01/29-04:00:00
2015/01/29-05:00:00
我尝试过以下方式:
for(var i = 0; i<6; i++){
console.log(moment(start_time,"YYYY/MM/DD-HH:mm:ss").add(1,'hour'));
}
但这行不通。我该怎么做?
最佳答案
你几乎成功了。
for(var i = 0; i<6; i++){ //make sure to actually use i!
console.log( //expects a string
moment(start_time,"YYYY/MM/DD-HH:mm:ss") //this works
.add(1,'hour') //this will return a moment object, not a string
);
}
所以改成
for(var i = 0; i<6; i++){
console.log(
moment(start_time,"YYYY/MM/DD-HH:mm:ss")
.add(i,'hour') //changed to i
.format('YYYY/MM/DD-HH:mm:ss') //make it a string
);
}
// Prints
// 2015/01/29-00:00:00
// 2015/01/29-01:00:00
// 2015/01/29-02:00:00
// 2015/01/29-03:00:00
// 2015/01/29-04:00:00
// 2015/01/29-05:00:00
关于javascript - 使用 moment 来操作日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28233759/