endOfMonth
Returns a new Date object set to the end of the month (last day, 23:59:59.999).
1/**
2 * Returns a new Date object set to the end of the month (last day, 23:59:59.999).
3 *
4 * @param date - The input date.
5 * @returns A new Date representing the end of the month.
6 */
7export function endOfMonth(date: Date): Date {
8 return new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59, 999);
9}
Precise Month-End Boundary
Sets the date to the last day of the month at
23:59:59.999
, covering the full extent of the month without overshooting.Handles Leap Years & Month Length Variability
Uses
new Date(year, month + 1, 0)
— a well-known pattern to get the last day of any month reliably (including February in leap years).Immutable Result
Returns a new
Date
object, keeping the input untouched — safe for use in pure functions or pipelines.Local Time Awareness
Aligns with user expectations in client-side applications, especially in filters and reports.
Tests | Examples
1test('endOfMonth - returns last day of month at 23:59:59.999', () => {
2 const input = new Date('2024-02-10T12:00:00.000Z'); // Leap year
3 const result = endOfMonth(input);
4
5 expect(result.getFullYear()).toBe(2024);
6 expect(result.getMonth()).toBe(1); // February
7 expect(result.getDate()).toBe(29); // Leap year
8 expect(result.getHours()).toBe(23);
9 expect(result.getMinutes()).toBe(59);
10 expect(result.getSeconds()).toBe(59);
11 expect(result.getMilliseconds()).toBe(999);
12});
13
14test('endOfMonth - does not mutate original date', () => {
15 const input = new Date('2023-04-20T08:00:00.000Z');
16 const copy = new Date(input.getTime());
17 endOfMonth(input);
18 expect(input).toEqual(copy);
19});
Common Use Cases
Range Filters for Monthly Reports
Define the inclusive upper boundary of a month when querying records or logs.
Billing and Subscription Logic
Set invoice or trial end dates to the precise end of a billing month.
Calendar Navigation
Highlight or scroll to the last day of a month in UI components.
Data Cleanup or Archival Cutoffs
Set precise boundaries for processing or migrating data based on month-end logic.
Validation Logic
Ensure no timestamp exceeds the end of the intended month.