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

roundToNearestMinute

Rounds a date to the nearest minute. If seconds >= 30, rounds up to the next minute. Otherwise, rounds down to the current minute.

TypeScript
Copied!
1/**
2 * Rounds a date to the nearest minute.
3 * If seconds >= 30, rounds up to the next minute.
4 * Otherwise, rounds down to the current minute.
5 *
6 * @param date - The input date.
7 * @returns A new Date rounded to the nearest minute.
8 */
9export function roundToNearestMinute(date: Date): Date {
10  const rounded = new Date(date);
11  rounded.setSeconds(0, 0);
12  
13  if (date.getSeconds() >= 30) {
14    rounded.setMinutes(rounded.getMinutes() + 1);
15  }
16  
17  return rounded;
18}
  • Precise Minute-Level Control

    Offers deterministic rounding logic that mirrors typical time rounding expectations (e.g., ≥30s rounds up).

  • Immutable Input

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

  • Milliseconds Handling

    Resets milliseconds alongside seconds, ensuring clean boundaries for scheduling and comparison.

  • Consistent Behavior

    Explicit logic avoids ambiguity compared to some third-party libraries’ rounding defaults.

Tests | Examples

TypeScript
Copied!
1test('rounds down when seconds < 30', () => {
2  const input = new Date('2025-06-27T12:34:15');
3  const expected = new Date('2025-06-27T12:34:00');
4  expect(roundToNearestMinute(input)).toEqual(expected);
5});
6
7test('rounds up when seconds >= 30', () => {
8  const input = new Date('2025-06-27T12:34:45');
9  const expected = new Date('2025-06-27T12:35:00');
10  expect(roundToNearestMinute(input)).toEqual(expected);
11});
12
13test('rounds correctly at end of hour', () => {
14  const input = new Date('2025-06-27T12:59:45');
15  const expected = new Date('2025-06-27T13:00:00');
16  expect(roundToNearestMinute(input)).toEqual(expected);
17});
18
19test('rounds correctly at start of minute', () => {
20  const input = new Date('2025-06-27T12:34:00');
21  const expected = new Date('2025-06-27T12:34:00');
22  expect(roundToNearestMinute(input)).toEqual(expected);
23});

Common Use Cases

  • Timestamps Normalization

    Clean up event timestamps to minute precision for database storage or comparison.

  • Time-Based Batching

    Group logs or analytics data into neat, rounded time intervals.

  • User-Friendly Display

    Show rounded appointment or action times in UI to improve readability.

  • Reminder and Alarm Scheduling

    Align actions or notifications to the nearest minute for better UX.

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