JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to get second Sunday of the month in JavaScript?

To get the second Sunday of the month, you need to go through the following steps:

  1. First, create a Date object and pass the 1st date of the month.

    Suppose you want to know the second Sunday of October, then start by creating a Date object like this, let d = new Date(2022, 9, 1);

    Note: JavaScript Date object follows zero-based numbering for months, so January is 0, February is 1, March is 2, and so on.

  2. Next, call the getDay() method on the Date object to know the day of the week on that date. If the value returned by the getDay() method is not equal to 0, subtract it from 7.

    if(d.getDay()>0){
      firstSunday = 7 - d.getDay();
    }else{
      firstSunday = 0;
    }
  3. After that, call the Date.getDate() method and add 7 and the value obtained in step 2 to it.

    secondSunday = d.getDate() + 7 + firstSunday
  4. Finally, call the setDate() method and pass the value obtained in step 3.

    d.setDate(secondSunday);
    

Following is the JavaScript code to get the second Sunday of the month:

let d = new Date(2018,9,1);
console.log(d.toString()); //"Mon Oct 01 2018 00:00:00 GMT+0530 (India Standard Time)"
if(d.getDay()>0){
  firstSunday = 7 - d.getDay();
}else{
  firstSunday = 0;
}
secondSunday = d.getDate() + 7 + firstSunday
d.setDate(secondSunday);
console.log(d.toString()); //"Sun Oct 14 2018 00:00:00 GMT+0530 (India Standard Time)"

The Date.getDay() method is used to know the day of the week for the Date object. It returns a value from 0 to 6 where 0 is Sunday, 1 is Monday, and so on.

Recommended Posts