Borislav Hadzhiev
Thu Jan 27 2022·2 min read
Photo by Meiying Ng
Use the Date()
constructor to get the first and last day of the current
year. The Date()
constructor takes the year, a zero-based value for the month
and the day as parameters and returns a Date
object.
const currentYear = new Date().getFullYear(); console.log(currentYear); // 👉️2022 const firstDay = new Date(currentYear, 0, 1); console.log(firstDay); // 👉️ Sat Jan 01 2022 const lastDay = new Date(currentYear, 11, 31); console.log(lastDay); // 👉️ Sat Dec 31 2022
We passed the following 3 parameters to the Date() constructor:
We used the Date.getFullYear method to get the current year.
0
, February is 1
, March is 2
, and so on, up to December, which is 11
.To get the first day of the current year, we passed 0
(January) for the month
and 1
for the day of the month to the Date()
constructor.
To get the last day of the current year, we passed 11
(December) for the month
and 31
for the day of the month.
31
for the day to get the last day of the year. A calendar year always starts on January 1st and ends December 31st.You can use this approach to get the first and last day for any year. All you
have to do is change the first parameter in the call to the Date()
constructor.
const year = 2030; const firstDay = new Date(year, 0, 1); console.log(firstDay); // 👉️ Tue Jan 01 2030 const lastDay = new Date(year, 11, 31); console.log(lastDay); // 👉️ Tue Dec 31 2030
If you want to make your code more readable, you can store the values for the month in variables with appropriate naming.
const currentYear = new Date().getFullYear(); const january = 0; const firstDay = new Date(currentYear, january, 1); console.log(firstDay); // 👉️ Sat Jan 01 2022 const december = 11; const lastDay = new Date(currentYear, december, 31); console.log(lastDay); // 👉️ Sat Dec 31 2022
Creating separated variables that store the zero-based value for the month makes our code a bit more readable.