MCPcopy
hub / github.com/date-fns/date-fns / roundToNearestHours

Function roundToNearestHours

pkgs/core/src/roundToNearestHours/index.ts:63–92  ·  view source on GitHub ↗
(
  date: DateArg<DateType>,
  options?: RoundToNearestHoursOptions<ResultDate>,
)

Source from the content-addressed store, hash-verified

61 * //=> Thu Jul 10 2014 08:00:00
62 */
63export function roundToNearestHours<
64 DateType extends Date,
65 ResultDate extends Date = DateType,
66>(
67 date: DateArg<DateType>,
68 options?: RoundToNearestHoursOptions<ResultDate>,
69): ResultDate {
70 const nearestTo = options?.nearestTo ?? 1;
71
72 if (nearestTo < 1 || nearestTo > 12)
73 return constructFrom(options?.in || date, NaN);
74
75 const date_ = toDate(date, options?.in);
76 const fractionalMinutes = date_.getMinutes() / 60;
77 const fractionalSeconds = date_.getSeconds() / 60 / 60;
78 const fractionalMilliseconds = date_.getMilliseconds() / 1000 / 60 / 60;
79 const hours =
80 date_.getHours() +
81 fractionalMinutes +
82 fractionalSeconds +
83 fractionalMilliseconds;
84
85 const method = options?.roundingMethod ?? "round";
86 const roundingMethod = getRoundingMethod(method);
87
88 const roundedHours = roundingMethod(hours / nearestTo) * nearestTo;
89
90 date_.setHours(roundedHours, 0, 0, 0);
91 return date_;
92}

Callers 1

test.tsFile · 0.90

Calls 3

constructFromFunction · 0.90
toDateFunction · 0.90
getRoundingMethodFunction · 0.90

Tested by

no test coverage detected