Open In App

Find 1st January be Sunday between a range of years in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are given a range of years, the task is to find the year having Sunday on 1st January.

Approach: We can use JavaScript Dates to get the years having Sunday on 1st January. In JavaScript, Date objects are based on a time value that is the number of milliseconds since 1 January 1970 UTC.

We can declare the Date object in the following way:

Example: In this program, we will use the last one. The new Date(year, month, day) will return the day, month, and year of the parameter given. 

Javascript




// Creating date object
// (Year , month , Day)
var A = new Date(2012, 0, 1);
  
// Printing the date
console.log(A);


Output:

Sun Jan 01 2012 00:00:00 GMT+0530 (India Standard Time)

After the creation of the Date object with given parameters, we can access the day of the week 0(Sunday) to 6(Saturday) from the getDay() function.

The getDay() method is used to get the day of the week for the specified date according to local time, where 0 represents Sunday.

Source Code:

HTML




<body>
    <h1>GeeksforGeeks</h1>
    <p id="geeks"></p>
  
    <label for="Year1">Year1:</label>
    <input type="number" id="year1" 
        name="Year1"><br><br>
  
    <label for="Year2">Year2:</label>
    <input type="number" id="year2" 
        name="Year2"><br><br>
  
    <button onClick="GFG_Fun()">
        Get Result
    </button>
    <p id="gfg"></p>
</body>


CSS




body {
    text-align: center;
}
  
h1 {
    color: green;
}
  
#geeks {
    font-size: 16px;
    font-weight: bold;
}
  
#gfg {
    color: green;
    font-size: 20px;
    font-weight: bold;
}


Javascript




let s = `Enter the value of Year1
and Year2 in the input box to get
year's having Sunday on 1st January`;
  
document.getElementById("geeks")
.innerHTML = `<p>${s}</p>`;
  
function GFG_Fun() {
var y1 = Number(document
.getElementById('year1').value);
  
var y2 = Number(document
.getElementById('year2').value);
  
var res = " ";
  
for (let year = y1; year <= y2; ++year) { 
    const c_year=new Date(year, 0, 1); 
    if (c_year.getDay()===0) { 
    res +=year + " ," ; 
    
    if (y1> y2) {
    document.getElementById('gfg').innerHTML
    = "Year2 must be greater than Year1";
    } else {
    if (res === " ") {
    document.getElementById('gfg')
    .innerHTML = `<p>No Year Exist</p>`;
    } else {
    document.getElementById('gfg')
    .innerHTML = `<p> Year having
        Sunday on 1st January are :${res}</p>`;
    }
    }
    }


Output: Click here to check the live output.

Find 1st January be Sunday between a range of years

Find 1st January be Sunday between a range of years



Last Updated : 13 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads