首页 > 解决方案 > 从现在到一天结束的所有时间

问题描述

所以我想把一天中所有剩余的时间分成一个数组,例如,如果实际时间是下午 3:00,我想有一个数组,例如 [4pm, 5pm, 6pm, 7pm, ... , 11pm]

我没有运气使用moment.js尝试了这样的事情

var now = moment().startOf('hour');
$('div').append(now + "<br>");
var count = 0;
while (now < moment().endOf('day')) {
  count += 30;
  now = now.add(count, 'minutes').format("hh:mm a");
  $('div').append(now + "<br>");
}

我怎样才能达到我想要的?

标签: javascriptmomentjs

解决方案


可以创建一个包含所有小时数的列表并删除n第一个条目,即n当前 24 小时时间,如下所示:

var now = moment().startOf('hour');
var all_hours=['12pm', '1am', '2am', '3am', '4am', '5am', '6am', '7am', '8am', '9am', '10am', '11am', '12am', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', '9pm', '10pm', '11pm'];
var remaining_hours=all_hours.slice(parseInt(now.format("H")), all_hours.length-1);

话虽如此,我认为您进行循环的原因是因为这是一个MVCE,而不是您在生产中真正要做的事情。因此,基于您的示例,以下内容应该有效

// Get current hour
var now = moment().startOf('hour');
// Get the 24 hour time
var this_hr_int24=parseInt(now.format("H"));
// The list to contain the remaining hours
var remaining_hours=[];
// Initialize loop variables
next_hr_int24=this_hr_int24;
next_hr=now;
// While the number in next_hr_int24 is less then 24
while (next_hr_int24 < parseInt(moment().endOf('day').format("H"))) {
  // Increase by 60
    var count = 60;
  // Next hour of day
  next_hr = next_hr.add(count, 'minutes')
  // Get the 24 hr time for the next hour
  next_hr_int24 = next_hr.format("H")
  // Get the am/pm value for the list
  next_hr_apm = next_hr.format("h a")

  remaining_hours.push(next_hr_apm);
}

推荐阅读