Get the next time that respect a time format and not a pervious one

断了今生、忘了曾经 提交于 2020-01-07 03:42:49

问题


I am trying to get the time to the next "6:00:00", I am using moment:

let shiftEnd =  moment("06:00:00", "HH:mm:ss")
console.log(shiftEnd.inspect())

It gets me the previous 6:00:00, the one with the same day as now().

moment("2017-07-31T06:00:00.000")

now() is:

moment("2017-07-31T12:20:57.076")

What's the best way to get the next 6am that's not passed yet?


回答1:


You are getting a moment object for the current day because, as moment Default section states:

You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds.

You can simply test if your moment object is in the past (using isBefore) and add 1 day if needed.

Here a live example:

let shiftEnd =  moment("06:00:00", "HH:mm:ss")

if( shiftEnd.isBefore(moment()) ){
  shiftEnd.add(1, 'd')
}

console.log(shiftEnd.inspect())
console.log(shiftEnd.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>



回答2:


You could use day method to get the current day of week number, and then add one to the day of the week to get tomorrow day of week:

    var now = moment(), day;

    // check if before 6 am get the current day, otherwise get tomorrow
    if(now.hour() < 6)
       day = now.day();
    else
       day = now.day() + 1;

Then to get tomorrow 6 am use isoWeekDay to get the moment object from the number of the day of week and set hour to 6 and minutes and seconds to 0:

var tomorrow = moment().isoWeekday(day).hour(6).minute(0).second(0)

tomorrow will be 2017-08-01T06:00:00+02:00



来源:https://stackoverflow.com/questions/45414587/get-the-next-time-that-respect-a-time-format-and-not-a-pervious-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!