Skip to content

roundDateTime

roundDateTime(value: string, options: { smallestUnit: SmallestUnit<DateTimeUnit>; roundingIncrement?: number; roundingMode?: RoundingMode; }): string

Round an ISO 8601 datetime string to the specified date-time unit.

  • Returns "" for invalid inputs.
  • Time units use Temporal.PlainDateTime.round() directly.
  • Date units (year, month, week) use manual start-of-unit rounding. Weeks start on Monday.
  • For date units the rounding grid is anchored at the unit containing value, so "halfEven" breaks an exact tie towards that unit’s start (multiple 0, the even one). Time units round through Temporal, which anchors half-even on its own absolute grid.
  • For date units the position within the unit is measured towards the next start, so a value in a unit that began before the first representable PlainDateTime (-271821-04-19T00:00:00.000000001) still rounds up to the next start. When it rounds down to that unrepresentable start, the result is "".
  • In the last representable year (+275760) a value that rounds down to a date unit still returns that unit’s start; only rounding up past +275760-09-13T23:59:59.999999999 returns "".
  • Wraps all Temporal calls in try-catch; returns "" on any error.
  • Output precision follows smallestUnit: no fractional seconds for “second” and coarser, 3 digits for “millisecond”, 6 for “microsecond” and 9 for “nanosecond”, so the result never hides the precision the unit asked for.
ParameterTypeDescription
valuestringISO 8601 datetime string

options

The unit to round to and how to round

OptionTypeDefaultDescription
smallestUnitDateTimeUnit | PluralUnit<DateTimeUnit> (DateTimeUnit)RequiredThe unit to round to, any date or time unit from "year" to "nanosecond", singular or plural, as Temporal’s GetTemporalUnitValuedOption accepts both. It also sets how many fractional-second digits the result is written with.
roundingIncrement?number1, Temporal’s default.How many units make one rounding step. For "day" and the time units Temporal requires it to divide the next larger unit evenly and be smaller than it (15 minutes, not 7 or 60; a day only by 1); for "year", "month" and "week" the steps are counted from the unit that holds value. A non-integer is truncated, and a value below 1 or not finite returns "".
roundingMode?"ceil" | "floor" | "expand" | "trunc" | "halfCeil" | "halfFloor" | "halfExpand" | "halfTrunc" | "halfEven""halfExpand", Temporal’s default.Which way a value between two steps goes: one of Temporal’s nine rounding modes, such as "floor", "ceil" or "halfExpand" (to the nearer step, a tie going up). Any other value returns "".

Rounded ISO 8601 datetime string, or "" on invalid input

import { roundDateTime } from "@northguild/gmt/plain/calculate";
roundDateTime("2024-06-15T12:34:56", { smallestUnit: "year" }) // "2024-01-01T00:00:00"
output 

plain/calculate/roundDateTime.ts