Open In App

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

Last Updated : 13 Jan, 2023
Like Article

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. 


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


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:


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


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


let s = `Enter the value of Year1
and Year2 in the input box to get
year's having Sunday on 1st January`;
.innerHTML = `<p>${s}</p>`;
function GFG_Fun() {
var y1 = Number(document
var y2 = Number(document
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) {
    = "Year2 must be greater than Year1";
    } else {
    if (res === " ") {
    .innerHTML = `<p>No Year Exist</p>`;
    } else {
    .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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads