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

startOfDay

Returns a new Date object set to the start of the given day (00:00:00.000).

TypeScript
Copied!
1/**
2 * Returns a new Date object set to the start of the given day (00:00:00.000).
3 *
4 * @param date - The input date.
5 * @returns A new Date representing the start of the day.
6 */
7export function startOfDay(date: Date): Date {
8  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
9}
  • Time-Stripping Precision

    Removes all time components (hours, minutes, seconds, milliseconds), isolating the date portion precisely.

  • Immutable Operation

    Returns a new Date instance without mutating the input, preserving function purity.

  • Timezone-Safe for Local Time

    Uses local date components, ensuring correct results according to the system’s local timezone.

  • Simple and Efficient

    Achieves the result using a single constructor call — no need for additional time manipulation methods.

Tests | Examples

TypeScript
Copied!
1test('startOfDay - resets time components', () => {
2  const input = new Date('2023-08-25T14:45:30.500Z');
3  const result = startOfDay(input);
4
5  expect(result.getFullYear()).toBe(2023);
6  expect(result.getMonth()).toBe(7); // August
7  expect(result.getDate()).toBe(25);
8  expect(result.getHours()).toBe(0);
9  expect(result.getMinutes()).toBe(0);
10  expect(result.getSeconds()).toBe(0);
11  expect(result.getMilliseconds()).toBe(0);
12});
13
14test('startOfDay - does not mutate original date', () => {
15  const input = new Date('2023-08-25T14:00:00.000Z');
16  const copy = new Date(input.getTime());
17  startOfDay(input);
18  expect(input).toEqual(copy); // original date remains unchanged
19});

Common Use Cases

  • Date-Only Comparisons

    Normalize timestamps to compare whether two dates fall on the same calendar day.

  • Daily Aggregations

    Group or bucket records by day in analytics or reporting.

  • UI Display or Selection Logic

    Set baseline values for calendars, filters, or default input fields.

  • Range Boundaries

    Define the beginning of a daily range when calculating durations or time windows.

  • Testing Date Logic

    Mock or align dates in tests where precise start-of-day values are needed.

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