Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the date for a specific day using javascript

Using the current date new Date(), I would like to calculate the date for the following Wednesday using Javascript.

For example, the current date is today:

"Sun Apr 18 2022 15:00:00 GMT"

What I would like to do is get the date for the following Wednesday, which would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"Wed Apr 20 2022 15:00:00 GMT"

If the current day is a Wednesday, I would like to calculate the date for the following Wednesday.

How could I achieve this?

>Solution :

Use the getDay method which will give day of the week (0 – 6, from sunday to saturday). (Wednesday is day 3)

function nextWednesday(date) {
  const day = date.getDay();
  // getDay returns between 0 - 6. Sunday - Saturday.
  // 3 is Wednesday
  let daysToAdd = 0;
  if (day < 3) {
    daysToAdd = 3 - day;
  } else {
    daysToAdd = 7 - day + 3;
  }
  return new Date(date.getTime() + daysToAdd * 24 * 60 * 60 * 1000);
}


const today = new Date();

console.log('today: ', today.toString());
console.log('following wednesday: ',  nextWednesday(today).toString())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading