index.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import getTimezoneOffsetInMilliseconds from "../_lib/getTimezoneOffsetInMilliseconds/index.js";
  2. import compareAsc from "../compareAsc/index.js";
  3. import toDate from "../toDate/index.js";
  4. import cloneObject from "../_lib/cloneObject/index.js";
  5. import defaultLocale from "../locale/en-US/index.js";
  6. import requiredArgs from "../_lib/requiredArgs/index.js";
  7. var MILLISECONDS_IN_MINUTE = 1000 * 60;
  8. var MINUTES_IN_DAY = 60 * 24;
  9. var MINUTES_IN_MONTH = MINUTES_IN_DAY * 30;
  10. var MINUTES_IN_YEAR = MINUTES_IN_DAY * 365;
  11. /**
  12. * @name formatDistanceStrict
  13. * @category Common Helpers
  14. * @summary Return the distance between the given dates in words.
  15. *
  16. * @description
  17. * Return the distance between the given dates in words, using strict units.
  18. * This is like `formatDistance`, but does not use helpers like 'almost', 'over',
  19. * 'less than' and the like.
  20. *
  21. * | Distance between dates | Result |
  22. * |------------------------|---------------------|
  23. * | 0 ... 59 secs | [0..59] seconds |
  24. * | 1 ... 59 mins | [1..59] minutes |
  25. * | 1 ... 23 hrs | [1..23] hours |
  26. * | 1 ... 29 days | [1..29] days |
  27. * | 1 ... 11 months | [1..11] months |
  28. * | 1 ... N years | [1..N] years |
  29. *
  30. * ### v2.0.0 breaking changes:
  31. *
  32. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  33. *
  34. * - The function was renamed from `distanceInWordsStrict` to `formatDistanceStrict`
  35. * to make its name consistent with `format` and `formatRelative`.
  36. *
  37. * - The order of arguments is swapped to make the function
  38. * consistent with `differenceIn...` functions.
  39. *
  40. * ```javascript
  41. * // Before v2.0.0
  42. *
  43. * distanceInWordsStrict(
  44. * new Date(2015, 0, 2),
  45. * new Date(2014, 6, 2)
  46. * ) //=> '6 months'
  47. *
  48. * // v2.0.0 onward
  49. *
  50. * formatDistanceStrict(
  51. * new Date(2014, 6, 2),
  52. * new Date(2015, 0, 2)
  53. * ) //=> '6 months'
  54. * ```
  55. *
  56. * - `partialMethod` option is renamed to `roundingMethod`.
  57. *
  58. * ```javascript
  59. * // Before v2.0.0
  60. *
  61. * distanceInWordsStrict(
  62. * new Date(1986, 3, 4, 10, 32, 0),
  63. * new Date(1986, 3, 4, 10, 33, 1),
  64. * { partialMethod: 'ceil' }
  65. * ) //=> '2 minutes'
  66. *
  67. * // v2.0.0 onward
  68. *
  69. * formatDistanceStrict(
  70. * new Date(1986, 3, 4, 10, 33, 1),
  71. * new Date(1986, 3, 4, 10, 32, 0),
  72. * { roundingMethod: 'ceil' }
  73. * ) //=> '2 minutes'
  74. * ```
  75. *
  76. * - If `roundingMethod` is not specified, it now defaults to `round` instead of `floor`.
  77. *
  78. * - `unit` option now accepts one of the strings:
  79. * 'second', 'minute', 'hour', 'day', 'month' or 'year' instead of 's', 'm', 'h', 'd', 'M' or 'Y'
  80. *
  81. * ```javascript
  82. * // Before v2.0.0
  83. *
  84. * distanceInWordsStrict(
  85. * new Date(1986, 3, 4, 10, 32, 0),
  86. * new Date(1986, 3, 4, 10, 33, 1),
  87. * { unit: 'm' }
  88. * )
  89. *
  90. * // v2.0.0 onward
  91. *
  92. * formatDistanceStrict(
  93. * new Date(1986, 3, 4, 10, 33, 1),
  94. * new Date(1986, 3, 4, 10, 32, 0),
  95. * { unit: 'minute' }
  96. * )
  97. * ```
  98. *
  99. * @param {Date|Number} date - the date
  100. * @param {Date|Number} baseDate - the date to compare with
  101. * @param {Object} [options] - an object with options.
  102. * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first
  103. * @param {'second'|'minute'|'hour'|'day'|'month'|'year'} [options.unit] - if specified, will force a unit
  104. * @param {'floor'|'ceil'|'round'} [options.roundingMethod='round'] - which way to round partial units
  105. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  106. * @returns {String} the distance in words
  107. * @throws {TypeError} 2 arguments required
  108. * @throws {RangeError} `date` must not be Invalid Date
  109. * @throws {RangeError} `baseDate` must not be Invalid Date
  110. * @throws {RangeError} `options.roundingMethod` must be 'floor', 'ceil' or 'round'
  111. * @throws {RangeError} `options.unit` must be 'second', 'minute', 'hour', 'day', 'month' or 'year'
  112. * @throws {RangeError} `options.locale` must contain `formatDistance` property
  113. *
  114. * @example
  115. * // What is the distance between 2 July 2014 and 1 January 2015?
  116. * const result = formatDistanceStrict(new Date(2014, 6, 2), new Date(2015, 0, 2))
  117. * //=> '6 months'
  118. *
  119. * @example
  120. * // What is the distance between 1 January 2015 00:00:15
  121. * // and 1 January 2015 00:00:00?
  122. * const result = formatDistanceStrict(
  123. * new Date(2015, 0, 1, 0, 0, 15),
  124. * new Date(2015, 0, 1, 0, 0, 0)
  125. * )
  126. * //=> '15 seconds'
  127. *
  128. * @example
  129. * // What is the distance from 1 January 2016
  130. * // to 1 January 2015, with a suffix?
  131. * const result = formatDistanceStrict(new Date(2015, 0, 1), new Date(2016, 0, 1), {
  132. * addSuffix: true
  133. * })
  134. * //=> '1 year ago'
  135. *
  136. * @example
  137. * // What is the distance from 1 January 2016
  138. * // to 1 January 2015, in minutes?
  139. * const result = formatDistanceStrict(new Date(2016, 0, 1), new Date(2015, 0, 1), {
  140. * unit: 'minute'
  141. * })
  142. * //=> '525600 minutes'
  143. *
  144. * @example
  145. * // What is the distance from 1 January 2015
  146. * // to 28 January 2015, in months, rounded up?
  147. * const result = formatDistanceStrict(new Date(2015, 0, 28), new Date(2015, 0, 1), {
  148. * unit: 'month',
  149. * roundingMethod: 'ceil'
  150. * })
  151. * //=> '1 month'
  152. *
  153. * @example
  154. * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?
  155. * import { eoLocale } from 'date-fns/locale/eo'
  156. * const result = formatDistanceStrict(new Date(2016, 7, 1), new Date(2015, 0, 1), {
  157. * locale: eoLocale
  158. * })
  159. * //=> '1 jaro'
  160. */
  161. export default function formatDistanceStrict(dirtyDate, dirtyBaseDate) {
  162. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  163. requiredArgs(2, arguments);
  164. var locale = options.locale || defaultLocale;
  165. if (!locale.formatDistance) {
  166. throw new RangeError('locale must contain localize.formatDistance property');
  167. }
  168. var comparison = compareAsc(dirtyDate, dirtyBaseDate);
  169. if (isNaN(comparison)) {
  170. throw new RangeError('Invalid time value');
  171. }
  172. var localizeOptions = cloneObject(options);
  173. localizeOptions.addSuffix = Boolean(options.addSuffix);
  174. localizeOptions.comparison = comparison;
  175. var dateLeft;
  176. var dateRight;
  177. if (comparison > 0) {
  178. dateLeft = toDate(dirtyBaseDate);
  179. dateRight = toDate(dirtyDate);
  180. } else {
  181. dateLeft = toDate(dirtyDate);
  182. dateRight = toDate(dirtyBaseDate);
  183. }
  184. var roundingMethod = options.roundingMethod == null ? 'round' : String(options.roundingMethod);
  185. var roundingMethodFn;
  186. if (roundingMethod === 'floor') {
  187. roundingMethodFn = Math.floor;
  188. } else if (roundingMethod === 'ceil') {
  189. roundingMethodFn = Math.ceil;
  190. } else if (roundingMethod === 'round') {
  191. roundingMethodFn = Math.round;
  192. } else {
  193. throw new RangeError("roundingMethod must be 'floor', 'ceil' or 'round'");
  194. }
  195. var milliseconds = dateRight.getTime() - dateLeft.getTime();
  196. var minutes = milliseconds / MILLISECONDS_IN_MINUTE;
  197. var timezoneOffset = getTimezoneOffsetInMilliseconds(dateRight) - getTimezoneOffsetInMilliseconds(dateLeft); // Use DST-normalized difference in minutes for years, months and days;
  198. // use regular difference in minutes for hours, minutes and seconds.
  199. var dstNormalizedMinutes = (milliseconds - timezoneOffset) / MILLISECONDS_IN_MINUTE;
  200. var unit;
  201. if (options.unit == null) {
  202. if (minutes < 1) {
  203. unit = 'second';
  204. } else if (minutes < 60) {
  205. unit = 'minute';
  206. } else if (minutes < MINUTES_IN_DAY) {
  207. unit = 'hour';
  208. } else if (dstNormalizedMinutes < MINUTES_IN_MONTH) {
  209. unit = 'day';
  210. } else if (dstNormalizedMinutes < MINUTES_IN_YEAR) {
  211. unit = 'month';
  212. } else {
  213. unit = 'year';
  214. }
  215. } else {
  216. unit = String(options.unit);
  217. } // 0 up to 60 seconds
  218. if (unit === 'second') {
  219. var seconds = roundingMethodFn(milliseconds / 1000);
  220. return locale.formatDistance('xSeconds', seconds, localizeOptions); // 1 up to 60 mins
  221. } else if (unit === 'minute') {
  222. var roundedMinutes = roundingMethodFn(minutes);
  223. return locale.formatDistance('xMinutes', roundedMinutes, localizeOptions); // 1 up to 24 hours
  224. } else if (unit === 'hour') {
  225. var hours = roundingMethodFn(minutes / 60);
  226. return locale.formatDistance('xHours', hours, localizeOptions); // 1 up to 30 days
  227. } else if (unit === 'day') {
  228. var days = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_DAY);
  229. return locale.formatDistance('xDays', days, localizeOptions); // 1 up to 12 months
  230. } else if (unit === 'month') {
  231. var months = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_MONTH);
  232. return months === 12 && options.unit !== 'month' ? locale.formatDistance('xYears', 1, localizeOptions) : locale.formatDistance('xMonths', months, localizeOptions); // 1 year up to max Date
  233. } else if (unit === 'year') {
  234. var years = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_YEAR);
  235. return locale.formatDistance('xYears', years, localizeOptions);
  236. }
  237. throw new RangeError("unit must be 'second', 'minute', 'hour', 'day', 'month' or 'year'");
  238. }