使用moment.js以24/12小时格式创建时间数组

时间:2020-01-23 12:17:50

标签: javascript momentjs

我刚刚在我的项目中添加了moment.js,并希望创建几个选择框,每个小时和半小时的时间。看起来像这样:

['12:00', '12:30', '1:00', '1:30', '2:00', '2:30'...'5:00', '5:30'];

我想知道是否有一种方法可以使moment.js生成数组的方式与生成星期几的方式相同:

moment.weekdays();

基本上,我想使用这些每小时选项作为标签和24小时格式的值来填充我的选择输入。我在这里最好的选择是什么?我要在循环中转换12小时时间,还是有一个更好的选择,即矩可以同时创建具有两个值的对象?无论哪种方式,我都很听。

1 个答案:

答案 0 :(得分:1)

您可以使用array#from创建时间数组

const hours = Array.from({
  length: 48
}, (_, hour) => moment({
    hour: Math.floor(hour / 2),
    minutes: (hour % 2 === 0 ? 0 : 30)
  }).format('HH:mm')
);
console.log(hours);
<script src="https://rawgit.com/moment/moment/2.24.0/min/moment.min.js"></script>