Get First and Last Day of the current Year in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 27, 2022

banner

Photo from Unsplash

Get First and Last Day of the current Year in JavaScript #

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.

index.js
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:

  1. The year
  2. The month
  3. The day

We used the Date.getFullYear method to get the current year.

The value for the month is zero-based, where January is 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.

We provided 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.

index.js
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.

index.js
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.