snippetjavascriptTip
Find the day, week, month, or quarter of the year using JavaScript
Viewed 0 times
javascriptyearquarterweekmonthfindtheusingday
Problem
JavaScript's
> [!NOTE]
>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
Finding the day of the year (in the range
Date API lacks a lot of methods for working with dates, which is why third-party date libraries are so popular. However, operations such as finding the day, week, month, or quarter of the year that a date corresponds to can be easily implemented without the use of libraries.> [!NOTE]
>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
Finding the day of the year (in the range
1-366) from a Date object is fairly straightforward. We can use the Date constructor and Date.prototype.getFullYear() to get the first day of the year as a Date object.Solution
const dayOfYear = date =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 86_400_000);
dayOfYear(new Date('2024-09-28')); // 272>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
Finding the day of the year (in the range
1-366) from a Date object is fairly straightforward. We can use the Date constructor and Date.prototype.getFullYear() to get the first day of the year as a Date object.Then, we can subtract the first day of the year from the given
date and divide with the milliseconds in each day to get the result. Finally, we can use Math.floor() to appropriately round the resulting day count to an integer.Calculating the week of the year also starts by calculating the first day of the year as a
Date object. We can then use Date.prototype.setDate(), Date.prototype.getDate() and Date.prototype.getDay() along with the modulo (%) operator to get the first Monday of the year.Finally, we can subtract the first Monday of the year from the given
date and divide with the number of milliseconds in a week. We can use Math.round() to get the zero-indexed week of the year corresponding to the given date. Negative zero (-0) is returned if the given date is before the first Monday of the year.Code Snippets
const dayOfYear = date =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 86_400_000);
dayOfYear(new Date('2024-09-28')); // 272const weekOfYear = date => {
const startOfYear = new Date(date.getFullYear(), 0, 1);
startOfYear.setDate(startOfYear.getDate() + (startOfYear.getDay() % 7));
return Math.round((date - startOfYear) / 604_800_000);
};
weekOfYear(new Date('2021-06-18')); // 23const monthOfYear = date => date.getMonth() + 1;
monthOfYear(new Date('2024-09-28')); // 9Context
From 30-seconds-of-code: day-week-month-quarter-of-year
Revisions (0)
No revisions yet.