Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get next date from weekday in JavaScript

How can one return the next date of a given weekday (it could be either a number 0-6 or names Sunday-Saturday).

Example, if today, on Friday 16-Oct-2009 I passed in:

  • Friday, it would return today's date 16-Oct-2009
  • Saturday returns 17-Oct-2009
  • Thursday returns 22-Oct-2009
like image 844
Ruslan Avatar asked Oct 16 '09 16:10

Ruslan


People also ask

How do I get the next Sunday in JavaScript?

function getSundayOfCurrentWeek() { const today = new Date(); const first = today. getDate() - today. getDay() + 1; const last = first + 6; const sunday = new Date(today. setDate(last)); return sunday; } // (today is Mon Jan 17 2022) // 👇️ Sun Jan 23 2022 console.

How do I get weekday in JavaScript?

JavaScript - Date getDay() Method Javascript date getDay() method returns the day of the week for the specified date according to local time. The value returned by getDay() is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.

How do you get the current week start date and end date in typescript?

You can also use following lines of code to get first and last date of the week: var curr = new Date; var firstday = new Date(curr. setDate(curr. getDate() - curr.


2 Answers

Just adding 7 doesn't solve the problem.

The below function will give you the next day of the week.

function nextDay(x){     var now = new Date();         now.setDate(now.getDate() + (x+(7-now.getDay())) % 7);     return now; } 
like image 123
Tim Avatar answered Sep 18 '22 12:09

Tim


Here's a slightly modified version to Tim's answer to address the specific question-- pass in a date d, and, and a desired day of week (dow 0-6), return the date

function nextDay(d, dow){     d.setDate(d.getDate() + (dow+(7-d.getDay())) % 7);     return d; } 
like image 31
NoelHunter Avatar answered Sep 17 '22 12:09

NoelHunter