【问题标题】:How to create an hours + minutes array with moment.js and ES6?如何使用 moment.js 和 ES6 创建小时 + 分钟数组?
【发布时间】:2019-05-20 22:08:57
【问题描述】:

我正在尝试使用 moment.js 和 ES6 在一天中以 30 分钟的间隔创建一个小时数组。

示例: let hours = ["12:00 AM", "12:30 AM", "1:00 AM", "1:30 AM", ..., "11:30 PM"]

我已经有了这个for 函数:

someFunction () {
  const items = []
  for (let hour = 0; hour < 24; hour++) {
    items.push(moment({ hour }).format('h:mm A'))
    items.push(moment({ hour, minute: 30 }).format('h:mm A'))
  }
  return items
}

但我想让它更像 ES6。

我已经走到这一步了:

someFunction () {
  let timeSlots = new Array(24).fill().map((acc, index) => {
    let items = []
    items.push(moment( index ).format('h:mm A'))
    items.push(moment({ index, minute: 30 }).format('h:mm A'))
  })
  return timeSlots
}

但它输出:

["1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", ...]

【问题讨论】:

    标签: javascript ecmascript-6 momentjs


    【解决方案1】:
    function someFunction () {
      const items = [];
      new Array(24).fill().forEach((acc, index) => {
        items.push(moment( {hour: index} ).format('h:mm A'));
        items.push(moment({ hour: index, minute: 30 }).format('h:mm A'));
      })
      return items;
    }
    

    【讨论】:

    • 我不敢相信它是如此简单。由于简单,答案被接受。
    • @Doge 这与类似 ES6 的代码无关,您希望用 24 个未定义值填充的数组在具有 forEach 的那些上循环...该代码如何比您的第一个示例更有用?
    【解决方案2】:

    这是工作代码:

    someFunction = () => {
      var items = []
      var currentDate = moment('12');
      new Array(48).fill().map((acc, index) => {
        items.push(currentDate.format('h:mm A'))
        currenDate = currentDate.add(30, 'minutes');
      })
      return items
    }
    
    console.log(someFunction());
    

    工作小提琴:http://jsfiddle.net/ekqxhwf4/1/

    【讨论】:

    • @Doge 这就是您正在寻找的解决方案吗?
    • 为什么需要 currentDate/moment 实例化?
    • currentDate 是从上午 12 点开始的 momentJs 对象。然后我们在 currentDate 上使用 momentjs 'add' 函数。我们知道 currentDate 总是 momentjs 对象。
    【解决方案3】:

    您可以使用Array.from 方法生成二维数组,然后使用扩展语法concat 创建一维数组。

    function create () {
      return [].concat(...Array.from(Array(24), (_, hour) => ([
        moment({hour}).format('h:mm A'),
        moment({ hour, minute: 30 }).format('h:mm A')
      ])))
    }
    
    console.log(create())
    &lt;script src="http://momentjs.com/downloads/moment.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案4】:

      您可以使用array#fromarray#reduce 生成30 分钟的间隔时间。

      let someFunction = () => {
        return Array.from({length: 24}, (_,i) => i).reduce((r,hour) => {
           r.push(moment({hour, minute: 0}).format('h:mm A'));
           r.push(moment({hour, minute: 30}).format('h:mm A'));
           return r;
        }, []);
      }
      console.log(someFunction());
      &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"&gt;&lt;/script&gt;

      【讨论】:

      • 代码 sn-p 结果抛出我相同的 [12:00AM, 12:30AM, 12:00AM, 12:30AM] 错误结果
      • 更新了解决方案。
      【解决方案5】:

      我知道momentJS是一个要求,但也可以用普通的JavaScript Date objects轻松解决:

      function everyXMilliseconds(x) {
        if (x === void 0) {
          x = 86400000;
        }
        var base = new Date(86400000);
        var currentDate = new Date(86400000);
        var dates = [];
        while (currentDate.getUTCDate() === base.getUTCDate()) {
          dates.push(new Date(currentDate.getTime()));
          currentDate.setTime(currentDate.getTime() + x);
        }
        return dates;
      }
      
      function everyXSeconds(x) {
        if (x === void 0) {
          x = 86400;
        }
        return everyXMilliseconds(x * 1000);
      }
      
      function everyXMinutes(x) {
        if (x === void 0) {
          x = 1440;
        }
        return everyXSeconds(x * 60);
      }
      
      function everyXHours(x) {
        if (x === void 0) {
          x = 24;
        }
        return everyXMinutes(x * 60);
      }
      //Offsets date with its own timezone difference
      function toLocalTime(date) {
        date.setUTCHours(date.getUTCHours() + date.getTimezoneOffset() / 60);
        return date;
      }
      //TEST
      //get dates
      var dates = everyXHours(0.5);
      // dates to time
      console.log('UTC times', dates.map(function(d) {
        return d.toLocaleTimeString("uk");
      }));
      // dates to time localized
      console.log('Local times', dates.map(toLocalTime).map(function(d) {
        return d.toLocaleTimeString("uk");
      }));

      我上面的 sn-p 有点过于复杂,但它说明你可以制作真正灵活的系统,而无需导入库。

      【讨论】:

        【解决方案6】:

        你可以通过标签获取值。

        function someFunction () {
          const items = [];
          new Array(24).fill().forEach((acc, index) => {
            items.push({"value": moment( {hour: index} ).format('HH:mm'), "label": moment( {hour: index} ).format('h:mm A')});
            items.push({"value": moment({ hour: index, minute: 30 }).format('HH:mm'), "label": moment({ hour: index, minute: 30 }).format('h:mm A')});
          })
          return items;
        }
        

        【讨论】:

          【解决方案7】:

          更短的版本是:

          const someFunction = () => 
            Array(48)
              .fill()
              .map((_, index) =>
                moment({
                  hour: Math.floor(0.5 * index),
                  minute: 30 * (index % 2)
                })
                .format("h:mm A"));
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-07-28
            相关资源
            最近更新 更多