Skip to content
Related Articles
Open in App
Not now

Related Articles

How to get the first day of the year in JavaScript ?

Improve Article
Save Article
  • Last Updated : 30 Dec, 2022
Improve Article
Save Article

Given a date/year and the task is to get the first day of the year using JavaScript. 

Approach 1:

  • Use getFullYear() Method to get the year from given date.
  • Use the new Date() function to create the new date object using year, month and day.

Example: This example uses the getFullYear() method to get the full year of the current day and then get the first day of that year. 

html




<body>
  
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
    <p id="GFG_UP">
    </p>
  
    <button onClick="GFG_Fun()">
        click here
    </button>
  
    <p id="GFG_DOWN">
    </p>
  
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
          
        var date = new Date();
              
        up.innerHTML = "Today = "+ date;
          
        function GFG_Fun() {
              
            // Use Date(year, month, day) function
            down.innerHTML = new Date(date.getFullYear(), 0, 1);
        }
    </script>
</body>

Output:

 

Approach 2:

  • Initialize the year to the variable (year = 2012).
  • Use new Date() function to create the new date object using year, month and day.

Example: This example uses the year 2012 and then get the first day of that year. 

html




<body>
  
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
    <p id="GFG_UP">
    </p>
  
    <button onClick="GFG_Fun()">
        click here
    </button>
  
    <p id="GFG_DOWN">
    </p>
  
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
          
        // Declare year and initialize it
        var year = 2023;
          
        up.innerHTML = "Today's year = "+ year;
          
        function GFG_Fun() {
              
            // Use Date(year, month, day) function
            // to get the first day of year
            down.innerHTML = new Date(year, 0, 1);
        }
    </script>
</body>

Output:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!