JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to get the first and last day of the current year in JavaScript?

The first day of every year is 1st January and the last day is 31st December.

To get the first and last day of the current year, follow the following steps:

  1. Create a Date object by calling the Date() constructor and don't pass any arguments.
  2. Get the current year using the getFullYear() method.
  3. After that, create two Date objects, firstDay, and lastDay.
  4. In the first Date object, specify 0 as the month and 1 as the date.
  5. In the second Date object, set 11 as the month and 31 as the date.
let d = new Date(),
    currentYear = d.getFullYear();

let firstDay = new Date(currentYear, 0, 1);
let lastDay = new Date(currentYear, 11, 31);

console.log(firstDay.toString()); //Sat Jan 01 2022
console.log(lastDay.toString()); //Sat Dec 31 2022

You can also use the steps mentioned in this tutorial in React and Angular to get the first and last day of the year.

The Date class follows zero-based numbering for months, which means January=0, February=1, March=2, ..., December=11.

Recommended Posts