Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

startOfMonth

Returns a new Date object set to the start of the month (1st, 00:00:00.000).

TypeScript
Copied!
1/**
2 * Returns a new Date object set to the start of the month (1st, 00:00:00.000).
3 *
4 * @param date - The input date.
5 * @returns A new Date representing the start of the month.
6 */
7export function startOfMonth(date: Date): Date {
8  return new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0);
9}
  • Accurate and Predictable

    Sets the date to the 1st of the month at 00:00:00.000, making it an ideal normalized lower bound for monthly comparisons.

  • Immutable

    Returns a fresh Date instance, ensuring the input remains unchanged.

  • Efficient Implementation

    Uses a single call to new Date(...) without extra calculations or adjustments.

  • Local Timezone Awareness

    Works in local time, matching expectations for UI logic and locale-specific behavior.

Tests | Examples

TypeScript
Copied!
1import { startOfMonth } from './startOfMonth';
2
3test('startOfMonth - returns first day of month at 00:00:00.000', () => {
4  const input = new Date('2023-08-25T15:30:00.000Z');
5  const result = startOfMonth(input);
6
7  expect(result.getFullYear()).toBe(2023);
8  expect(result.getMonth()).toBe(7); // August
9  expect(result.getDate()).toBe(1);
10  expect(result.getHours()).toBe(0);
11  expect(result.getMinutes()).toBe(0);
12  expect(result.getSeconds()).toBe(0);
13  expect(result.getMilliseconds()).toBe(0);
14});
15
16test('startOfMonth - does not mutate original date', () => {
17  const input = new Date('2023-08-25T10:00:00.000Z');
18  const copy = new Date(input.getTime());
19  startOfMonth(input);
20  expect(input).toEqual(copy);
21});

Common Use Cases

  • Monthly Range Filtering

    Determine the starting point for filtering data within a given month (e.g. sales, events, logs).

  • Calendar UI Initialization

    Scroll or focus on the beginning of the month when rendering calendar views.

  • Time Series Aggregation

    Use as a grouping key for monthly data summaries or analytics.

  • Date Validation

    Check if a given date is at or after the beginning of a month.

  • Scheduling and Billing

    Anchor logic for recurring monthly tasks, charges, or reports.

Codebase: Utilities -> Dates -> startOfMonth | Yevhen Klymentiev