get the date for the first day of the current decade in javascript

index.tsx
let today = new Date();
let year = today.getFullYear() - today.getFullYear() % 10;
let decadeStart = new Date(year, 0, 1); // Month is zero-based
console.log(decadeStart);
172 chars
5 lines

Explanation:

  • In the first line, we create a new Date object using the constructor.
  • In the second line, we get the current year using getFullYear() and subtract the remainder when divided by 10. For example, if the current year is 2021, then 2021 % 10 will give us 1, so we subtract 1 from 2021 to get the year 2020, which is the start of the current decade.
  • In the third line, we create a new Date object using the year we calculated, with the month set to 0 (which represents January) and the day set to 1.
  • Finally, we log the result to the console.

gistlibby LogSnag