【问题标题】:Get hours between two times in moment.js在 moment.js 中获取两次之间的小时数
【发布时间】:2019-10-26 12:21:06
【问题描述】:

我尝试这样:

let fromTime = '17:00'
let toTime = '20:00'
let a=[]
for(let i=parseInt(fromTime);i<parseInt(toTime);i++){
  a.push({time: i+':00'})
}
console.log(a)

它有效。但这是最好的方法吗?

moment js 的最佳使用方式是什么?

【问题讨论】:

    标签: javascript jquery time momentjs


    【解决方案1】:

    有点,但你可以得到更好的结果。首先将您的时间转换为 moment.js object 然后得到 fromTimetoTime 之间的差异,然后将差异作为小时,最后在循环中添加一小时的差异。

    let fromTime = moment('17:00', 'HH:mm');
    let toTime = moment('20:00', 'HH:mm');
    let duration = moment.duration(toTime.diff(fromTime));
    let diff = duration.hours();
    let array = [];
    
    for (i = 0; diff > i; i++) {
      let result = moment(fromTime).add(i, 'hours').format('HH:mm')
      array.push({
        result
      })
    }
    
    console.log(array)
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"&gt;&lt;/script&gt;

    有一件事,在fromto 时间之间获取确切的时间是有意义的,因此您可以将i=1 设置为仅获取:

    [
      {
        "result": "18:00"
      },
      {
        "result": "19:00"
      }
    ]
    

    【讨论】:

      【解决方案2】:

      我建议使用 js-joda 库,而不是 moment js。

      import {LocalTime } from '@js-joda/core'
      
      const start = LocalTime.parse("10:00")
      const end = LocalTime.parse("20:30")
      
      const times = [];
      
      for (let time = start; time.compareTo(end) < 0; time = time.plusHours(1) ) {
        times.push(time.toString());
      }
      
      console.log(times);
      

      https://js-joda.github.io/js-joda/manual/LocalTime.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        • 2013-08-28
        • 2012-12-05
        相关资源
        最近更新 更多