gpt4 book ai didi

javascript - 使用 moment.js 创建过去 24 小时的数组

转载 作者:行者123 更新时间:2023-11-28 17:31:46 25 4
gpt4 key购买 nike

我正在尝试在 Moment.js 中创建过去 24 小时的数组,其值只是 AM/PM 后面的小时数(不是分钟、秒,甚至是日历日期)。

它现在可以工作,但是当我只需要以小时为单位的时间时,它会在每个元素中给出完整的日期数据(Sun May 06 2018 22:24:29 GMT-0700):

JS 代码:

var hoursPerDay = 24;
var time = [];

function timeOneDay() {
var formattedTime;
for (i = 0; i < hoursPerDay + 1; i++) { //fill in all of the hours
formattedTime = (moment().subtract(i, "hours"));
formattedTime.format("hA"); //give the time in format X AM/PM
time.unshift(formattedTime); //add to beginning of array
} //do this for all 24 hours
}
timeOneDay();
console.log(time);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

最佳答案

moment.format() 返回格式化值。您没有将其存储在变量中

var hoursPerDay = 24;
var time = [];

function timeOneDay(){
var formattedTime;
for(i =0; i < hoursPerDay+1 ; i++){ //fill in all of the hours
formattedTime = (moment().subtract(i, "hours")).format("hA"); //give the time in format X AM/PM
time.unshift(formattedTime); //add to beginning of array
} //do this for all 24 hours
}
timeOneDay();
console.log(time);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

关于javascript - 使用 moment.js 创建过去 24 小时的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50208190/

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