roundToNearestMinutes.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { getRoundingMethod } from "./_lib/getRoundingMethod.js";
  2. import { constructFrom } from "./constructFrom.js";
  3. import { toDate } from "./toDate.js";
  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. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  18. *
  19. * @param date - The date to round
  20. * @param options - An object with options.
  21. *
  22. * @returns The new date rounded to the closest minute
  23. *
  24. * @example
  25. * // Round 10 July 2014 12:12:34 to nearest minute:
  26. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34))
  27. * //=> Thu Jul 10 2014 12:13:00
  28. *
  29. * @example
  30. * // Round 10 July 2014 12:12:34 to nearest quarter hour:
  31. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 })
  32. * //=> Thu Jul 10 2014 12:15:00
  33. *
  34. * @example
  35. * // Floor (rounds down) 10 July 2014 12:12:34 to nearest minute:
  36. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'floor' })
  37. * //=> Thu Jul 10 2014 12:12:00
  38. *
  39. * @example
  40. * // Ceil (rounds up) 10 July 2014 12:12:34 to nearest half hour:
  41. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'ceil', nearestTo: 30 })
  42. * //=> Thu Jul 10 2014 12:30:00
  43. */
  44. export function roundToNearestMinutes(date, options) {
  45. const nearestTo = options?.nearestTo ?? 1;
  46. if (nearestTo < 1 || nearestTo > 30) return constructFrom(date, NaN);
  47. const date_ = toDate(date, options?.in);
  48. const fractionalSeconds = date_.getSeconds() / 60;
  49. const fractionalMilliseconds = date_.getMilliseconds() / 1000 / 60;
  50. const minutes =
  51. date_.getMinutes() + fractionalSeconds + fractionalMilliseconds;
  52. const method = options?.roundingMethod ?? "round";
  53. const roundingMethod = getRoundingMethod(method);
  54. const roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo;
  55. date_.setMinutes(roundedMinutes, 0, 0);
  56. return date_;
  57. }
  58. // Fallback for modularized imports:
  59. export default roundToNearestMinutes;