index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import toDate from "../toDate/index.js";
  2. import toInteger from "../_lib/toInteger/index.js";
  3. /**
  4. * @name roundToNearestMinutes
  5. * @category Minute Helpers
  6. * @summary Rounds the given date to the nearest minute
  7. *
  8. * @description
  9. * Rounds the given date to the nearest minute (or number of minutes).
  10. * Rounds up when the given date is exactly between the nearest round minutes.
  11. *
  12. * ### v2.0.0 breaking changes:
  13. *
  14. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  15. *
  16. * @param {Date|Number} date - the date to round
  17. * @param {Object} [options] - an object with options.
  18. * @param {Number} [options.nearestTo=1] - nearest number of minutes to round to. E.g. `15` to round to quarter hours.
  19. * @returns {Date} the new date rounded to the closest minute
  20. * @throws {TypeError} 1 argument required
  21. * @throws {RangeError} `options.nearestTo` must be between 1 and 30
  22. *
  23. * @example
  24. * // Round 10 July 2014 12:12:34 to nearest minute:
  25. * var 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:07:30 to nearest quarter hour:
  30. * var result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 })
  31. * // rounds up because given date is exactly between 12:00:00 and 12:15:00
  32. * //=> Thu Jul 10 2014 12:15:00
  33. */
  34. export default function roundToNearestMinutes(dirtyDate, options) {
  35. if (arguments.length < 1) {
  36. throw new TypeError('1 argument required, but only none provided present');
  37. }
  38. var nearestTo = options && 'nearestTo' in options ? toInteger(options.nearestTo) : 1;
  39. if (nearestTo < 1 || nearestTo > 30) {
  40. throw new RangeError('`options.nearestTo` must be between 1 and 30');
  41. }
  42. var date = toDate(dirtyDate);
  43. var seconds = date.getSeconds(); // relevant if nearestTo is 1, which is the default case
  44. var minutes = date.getMinutes() + seconds / 60;
  45. var roundedMinutes = Math.floor(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. }