Get the next week on a specific day in JavaScript

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

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 is the date "Thu Apr 27 2017 21:00:00 GMT" (Thursday, but in 7 hours), I am looking for the result:

Thu May 4 2017 19:00:00 GMT

Any help would be greatly appreciated!

+4
source share
3 answers

Maybe something like the following (you can extend it if you want a more specific time than an hour or a 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
Run codeHide result

now.getDate() + (7 + dayOfWeek - now.getDay()) % 7, ( ), ( % 7, if (result < now), , , .

+1

. , .js , .

var d = new Date();
var n = d.getTime(); // n == time in milliseconds since 1st Jan 1970
var weekday = d.GetDay() // 0...6 ; 0 == Sunday, 6 = Saturday, 4 = Thursday
var numDaysToNextThursday = weekday >= 4 ? 7 - (weekday-4) : 4 - weekday;
var nextThursday_msecs = n + numDaysToNextThursday * 24 * 60 * 60 * 1000;
var theDate = new Date(nextThursday_msecs); // this is the date

: , 7PM - . ; 7 , , . , .

+1

, .

7 - 4 - - ,

var day = new Date();

var days = 7 - day.getDay() + 4;

var nextDay = new Date(day.setDate(day.getDate() + days)); 


console.log(nextDay.toString());
Hide result

codepen https://codepen.io/kejt/pen/LyRGBX?editors=1111

0

Source: https://habr.com/ru/post/1675495/


All Articles