70f885de2a9ec89249a4a2d974bc4f84a65f20ff521359cadb8156b15cbc5e039760e0d297866378d40b3de1924eea7b4d984e8109d0293c73bacc144c3fbf 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import absFloor from '../utils/abs-floor';
  2. import { cloneWithOffset } from '../units/offset';
  3. import { normalizeUnits } from '../units/aliases';
  4. export function diff(input, units, asFloat) {
  5. var that, zoneDelta, output;
  6. if (!this.isValid()) {
  7. return NaN;
  8. }
  9. that = cloneWithOffset(input, this);
  10. if (!that.isValid()) {
  11. return NaN;
  12. }
  13. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  14. units = normalizeUnits(units);
  15. switch (units) {
  16. case 'year':
  17. output = monthDiff(this, that) / 12;
  18. break;
  19. case 'month':
  20. output = monthDiff(this, that);
  21. break;
  22. case 'quarter':
  23. output = monthDiff(this, that) / 3;
  24. break;
  25. case 'second':
  26. output = (this - that) / 1e3;
  27. break; // 1000
  28. case 'minute':
  29. output = (this - that) / 6e4;
  30. break; // 1000 * 60
  31. case 'hour':
  32. output = (this - that) / 36e5;
  33. break; // 1000 * 60 * 60
  34. case 'day':
  35. output = (this - that - zoneDelta) / 864e5;
  36. break; // 1000 * 60 * 60 * 24, negate dst
  37. case 'week':
  38. output = (this - that - zoneDelta) / 6048e5;
  39. break; // 1000 * 60 * 60 * 24 * 7, negate dst
  40. default:
  41. output = this - that;
  42. }
  43. return asFloat ? output : absFloor(output);
  44. }
  45. function monthDiff(a, b) {
  46. if (a.date() < b.date()) {
  47. // end-of-month calculations work correct when the start month has more
  48. // days than the end month.
  49. return -monthDiff(b, a);
  50. }
  51. // difference in months
  52. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
  53. // b is in (anchor - 1 month, anchor + 1 month)
  54. anchor = a.clone().add(wholeMonthDiff, 'months'),
  55. anchor2,
  56. adjust;
  57. if (b - anchor < 0) {
  58. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  59. // linear across the month
  60. adjust = (b - anchor) / (anchor - anchor2);
  61. } else {
  62. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  63. // linear across the month
  64. adjust = (b - anchor) / (anchor2 - anchor);
  65. }
  66. //check for negative zero, return zero if negative zero
  67. return -(wholeMonthDiff + adjust) || 0;
  68. }