【问题标题】:Create an array of the last 24 hours using moment.js使用 moment.js 创建过去 24 小时的数组
【发布时间】:2018-05-07 06:26:00
【问题描述】:

我正在尝试在 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);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"&gt;&lt;/script&gt;

【问题讨论】:

    标签: javascript arrays datetime momentjs


    【解决方案1】:

    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);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2012-10-30
      • 2012-10-09
      • 1970-01-01
      • 2016-10-08
      • 2018-09-12
      相关资源
      最近更新 更多