0

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?

Assem
  • 11,574
  • 5
  • 59
  • 97

2 Answers2

1

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

amicoderozer
  • 2,046
  • 6
  • 28
  • 44
  • this solution fails if it's 5am for example – Assem Jul 31 '17 at 12:07
  • yes, but you can simply check the current hour with hour method ( moment().hour()), and if it's less then 6 get the current day otherwise get the next. Updated my answer – amicoderozer Jul 31 '17 at 12:36
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>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112