How to get the first day of the year in JavaScript ?
Last Updated :
12 Jun, 2023
Improve
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 the 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.
let date = new Date();
console.log("Today = " + date);
// Use Date(year, month, day) function
console.log(new Date(date.getFullYear(), 0, 1));
Output
Today = Mon Jun 12 2023 02:10:43 GMT+0000 (Coordinated Universal Time) 2023-01-01T00:00:00.000Z
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 2023 and then get the first day of that year.
let year = 2023;
console.log("Today's year = " + year);
// Use Date(year, month, day) function
// to get the first day of year
console.log(new Date(year, 0, 1));
Output
Today's year = 2023 2023-01-01T00:00:00.000Z