gpt4 book ai didi

javascript - 使用 moment 来操作日期和时间

转载 作者:行者123 更新时间:2023-11-30 00:33:34 26 4
gpt4 key购买 nike

我使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com