Borislav Hadzhiev
Mon Oct 25 2021·2 min read
Photo by Jeremy Bishop
To get the first day of a year, use the Date()
constructor to create a date
object, passing it a call to the getFullYear()
method for the year, 0
for
the month, and 1
for the day as parameters. The Date
object will contain the
first day of the year.
function getFirstDayOfYear(year) { return new Date(year, 0, 1); } // 👇️ Current Year const currentYear = new Date().getFullYear(); // 👇️ Sat Jan 01 2022 console.log(getFirstDayOfYear(currentYear)); // 👇️ Year 2025 console.log(getFirstDayOfYear(2025)); // 👉️ Wed Jan 01 2025
We passed the following 3 parameters to the Date() constructor:
We used the Date.getFullYear method to get the current year.
For the month, we hard coded 0
because we want the first month of the year.
0
is January and 11
is December.We provided 1
for the day because we want the first day of the year.
The getFirstDayOfYear
function works for any year, here are some examples.
function getFirstDayOfYear(year) { return new Date(year, 0, 1); } // 👇️ Current Year const currentYear = new Date().getFullYear(); // 👇️ Sat Jan 01 2022 console.log(getFirstDayOfYear(currentYear)); console.log(getFirstDayOfYear(2027)); // 👉️ Fri Jan 01 2027 console.log(getFirstDayOfYear(2030)); // 👉️ Tue Jan 01 2030 console.log(getFirstDayOfYear(2035)); // 👉️ Mon Jan 01 2035
The only tricky thing here is to remember that months are zero-based and go from
0
(January) to 11
(December).
If you want to make the function easier to read, you can extract the month in a variable:
function getFirstDayOfYear(year) { const january = 0; return new Date(year, january, 1); }