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.
Javascript
let date = new Date();
console.log( "Today = " + date);
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.
Javascript
let year = 2023;
console.log( "Today's year = " + year);
console.log( new Date(year, 0, 1));
|
Output
Today's year = 2023
2023-01-01T00:00:00.000Z
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!