Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get next week's date of a certain day in JavaScript

Tags:

javascript

Depending on today's date (new Date()), I would like to get the date of the next Thursday at 7pm in javascript. For example:

If today's date is "Mon Apr 24 2017 13:00:00 GMT" I am looking for the result:

Thu Apr 27 2017 19:00:00 GMT

However, if today's date is "Thu Apr 27 2017 21:00:00 GMT" (a Thursday, but past 7pm) I am looking for the result:

Thu May 4 2017 19:00:00 GMT

Any help would be much appreciated!

like image 362
ericalli Avatar asked Apr 24 '17 07:04

ericalli


1 Answers

Maybe something like the following (you can extend it if you want a more specific time than just hour and minute):

// day: 0=Sunday, 1=Monday...4=Thursday...
function nextDayAndTime(dayOfWeek, hour, minute) {
  var now = new Date()
  var result = new Date(
                 now.getFullYear(),
                 now.getMonth(),
                 now.getDate() + (7 + dayOfWeek - now.getDay()) % 7,
                 hour,
                 minute)

  if (result < now)
    result.setDate(result.getDate() + 7)
  
  return result
}

console.log(nextDayAndTime(4, 19, 0).toString()) // Thursday 7pm
console.log(nextDayAndTime(0, 19, 0).toString()) // Sunday 7pm
console.log(nextDayAndTime(1, 19, 0).toString()) // Monday 7pm (later today as of now in my timezone)
console.log(nextDayAndTime(1, 7, 30).toString()) // Monday 7:30am (next week, in my timezone)
console.log(nextDayAndTime(2, 19, 0).toString()) // Tuesday 7pm

The two key bits are now.getDate() + (7 + dayOfWeek - now.getDay()) % 7, which figures out the next Thursday (or specified day) starting from today (that's what the % 7 does, and then the if (result < now) that double-checks if the required time has passed yet today and if so adds a week.

like image 128
nnnnnn Avatar answered Oct 14 '22 08:10

nnnnnn