简体   繁体   English

如何使用 moment.js 和 ES6 创建小时 + 分钟数组?

[英]How to create an hours + minutes array with moment.js and ES6?

I'm trying to create an array of hours in a day with 30 minute intervals with moment.js and ES6.我正在尝试使用 moment.js 和 ES6 在一天中以 30 分钟的间隔创建一个小时数组。

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

I already have this for function:我已经有了这个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
}

But I would like to make it more ES6-like.但我想让它更像 ES6。

I have gotten this far:我已经走到这一步了:

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
}

But it outputs:但它输出:

["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", ...]

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;
}

You can use array#from with array#reduce to generate 30 minutes interval time.您可以使用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());
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

here is working code:这是工作代码:

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());

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

You could use Array.from method to generate 2d array and then concat with spread syntax to create 1d array.您可以使用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())
 <script src="http://momentjs.com/downloads/moment.js"></script>

I know momentJS was a requirement, but could also be easily solved with ordinary JavaScript Date objects :我知道momentJS是必需的,但也可以用普通的JavaScript Date 对象轻松解决:

 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"); }));

My snippet above is bit overly complicated, but it illustrates that you can make really flexible system without need to import libraries.我上面的代码片段有点过于复杂,但它说明了您可以创建真正灵活的系统而无需导入库。

you can get the value with the label.您可以通过标签获得价值。

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;
}

An even shorter version would be:一个更短的版本是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM