02436087309c8b437fc4794298b1a04711f943cf38f81d032b90f7ee7298b6841c2d079f4ae7d1c8b0e918e541decfe6c5aeeed40d5d1fb6f8267a2492a35a 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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,
  6. zoneDelta,
  7. delta, output;
  8. if (!this.isValid()) {
  9. return NaN;
  10. }
  11. that = cloneWithOffset(input, this);
  12. if (!that.isValid()) {
  13. return NaN;
  14. }
  15. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  16. units = normalizeUnits(units);
  17. if (units === 'year' || units === 'month' || units === 'quarter') {
  18. output = monthDiff(this, that);
  19. if (units === 'quarter') {
  20. output = output / 3;
  21. } else if (units === 'year') {
  22. output = output / 12;
  23. }
  24. } else {
  25. delta = this - that;
  26. output = units === 'second' ? delta / 1e3 : // 1000
  27. units === 'minute' ? delta / 6e4 : // 1000 * 60
  28. units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
  29. units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  30. units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  31. delta;
  32. }
  33. return asFloat ? output : absFloor(output);
  34. }
  35. function monthDiff (a, b) {
  36. // difference in months
  37. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  38. // b is in (anchor - 1 month, anchor + 1 month)
  39. anchor = a.clone().add(wholeMonthDiff, 'months'),
  40. anchor2, adjust;
  41. if (b - anchor < 0) {
  42. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  43. // linear across the month
  44. adjust = (b - anchor) / (anchor - anchor2);
  45. } else {
  46. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  47. // linear across the month
  48. adjust = (b - anchor) / (anchor2 - anchor);
  49. }
  50. //check for negative zero, return zero if negative zero
  51. return -(wholeMonthDiff + adjust) || 0;
  52. }