roundToNearestMinutes.mjs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { getRoundingMethod } from "./_lib/getRoundingMethod.mjs";
  2. import { constructFrom } from "./constructFrom.mjs";
  3. import { toDate } from "./toDate.mjs";
  4. /**
  5. * The {@link roundToNearestMinutes} function options.
  6. */
  7. /**
  8. * @name roundToNearestMinutes
  9. * @category Minute Helpers
  10. * @summary Rounds the given date to the nearest minute
  11. *
  12. * @description
  13. * Rounds the given date to the nearest minute (or number of minutes).
  14. * Rounds up when the given date is exactly between the nearest round minutes.
  15. *
  16. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  17. *
  18. * @param date - The date to round
  19. * @param options - An object with options.
  20. *
  21. * @returns The new date rounded to the closest minute
  22. *
  23. * @example
  24. * // Round 10 July 2014 12:12:34 to nearest minute:
  25. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34))
  26. * //=> Thu Jul 10 2014 12:13:00
  27. *
  28. * @example
  29. * // Round 10 July 2014 12:12:34 to nearest quarter hour:
  30. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 })
  31. * //=> Thu Jul 10 2014 12:15:00
  32. *
  33. * @example
  34. * // Floor (rounds down) 10 July 2014 12:12:34 to nearest minute:
  35. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'floor' })
  36. * //=> Thu Jul 10 2014 12:12:00
  37. *
  38. * @example
  39. * // Ceil (rounds up) 10 July 2014 12:12:34 to nearest half hour:
  40. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'ceil', nearestTo: 30 })
  41. * //=> Thu Jul 10 2014 12:30:00
  42. */
  43. export function roundToNearestMinutes(date, options) {
  44. const nearestTo = options?.nearestTo ?? 1;
  45. if (nearestTo < 1 || nearestTo > 30) return constructFrom(date, NaN);
  46. const _date = toDate(date);
  47. const fractionalSeconds = _date.getSeconds() / 60;
  48. const fractionalMilliseconds = _date.getMilliseconds() / 1000 / 60;
  49. const minutes =
  50. _date.getMinutes() + fractionalSeconds + fractionalMilliseconds;
  51. // Unlike the `differenceIn*` functions, the default rounding behavior is `round` and not 'trunc'
  52. const method = options?.roundingMethod ?? "round";
  53. const roundingMethod = getRoundingMethod(method);
  54. const roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo;
  55. const result = constructFrom(date, _date);
  56. result.setMinutes(roundedMinutes, 0, 0);
  57. return result;
  58. }
  59. // Fallback for modularized imports:
  60. export default roundToNearestMinutes;