index.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import toDate from "../toDate/index.js";
  2. import { getRoundingMethod } from "../_lib/roundingMethods/index.js";
  3. import toInteger from "../_lib/toInteger/index.js";
  4. /**
  5. * @name roundToNearestMinutes
  6. * @category Minute Helpers
  7. * @summary Rounds the given date to the nearest minute
  8. *
  9. * @description
  10. * Rounds the given date to the nearest minute (or number of minutes).
  11. * Rounds up when the given date is exactly between the nearest round minutes.
  12. *
  13. * @param {Date|Number} date - the date to round
  14. * @param {Object} [options] - an object with options.
  15. * @param {Number} [options.nearestTo=1] - nearest number of minutes to round to. E.g. `15` to round to quarter hours.
  16. * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`)
  17. * @returns {Date} the new date rounded to the closest minute
  18. * @throws {TypeError} 1 argument required
  19. * @throws {RangeError} `options.nearestTo` must be between 1 and 30
  20. *
  21. * @example
  22. * // Round 10 July 2014 12:12:34 to nearest minute:
  23. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34))
  24. * //=> Thu Jul 10 2014 12:13:00
  25. *
  26. * @example
  27. * // Round 10 July 2014 12:07:30 to nearest quarter hour:
  28. * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 })
  29. * // rounds up because given date is exactly between 12:00:00 and 12:15:00
  30. * //=> Thu Jul 10 2014 12:15:00
  31. */
  32. export default function roundToNearestMinutes(dirtyDate, options) {
  33. var _options$nearestTo;
  34. if (arguments.length < 1) {
  35. throw new TypeError('1 argument required, but only none provided present');
  36. }
  37. var nearestTo = toInteger((_options$nearestTo = options === null || options === void 0 ? void 0 : options.nearestTo) !== null && _options$nearestTo !== void 0 ? _options$nearestTo : 1);
  38. if (nearestTo < 1 || nearestTo > 30) {
  39. throw new RangeError('`options.nearestTo` must be between 1 and 30');
  40. }
  41. var date = toDate(dirtyDate);
  42. var seconds = date.getSeconds(); // relevant if nearestTo is 1, which is the default case
  43. var minutes = date.getMinutes() + seconds / 60;
  44. var roundingMethod = getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod);
  45. var roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo;
  46. var remainderMinutes = minutes % nearestTo;
  47. var addedMinutes = Math.round(remainderMinutes / nearestTo) * nearestTo;
  48. return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), roundedMinutes + addedMinutes);
  49. }