36f0f8256732641f874cebfd40ea31926f0b4d77c244f505df220f1f02f0b5ffa33fd4719b04f460d8ee0e2908ce9cc2bd474198ec51994f8f91fbc09740ec 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { daysToMonths, monthsToDays } from './bubble';
  2. import { normalizeUnits } from '../units/aliases';
  3. export function as(units) {
  4. if (!this.isValid()) {
  5. return NaN;
  6. }
  7. var days,
  8. months,
  9. milliseconds = this._milliseconds;
  10. units = normalizeUnits(units);
  11. if (units === 'month' || units === 'quarter' || units === 'year') {
  12. days = this._days + milliseconds / 864e5;
  13. months = this._months + daysToMonths(days);
  14. switch (units) {
  15. case 'month':
  16. return months;
  17. case 'quarter':
  18. return months / 3;
  19. case 'year':
  20. return months / 12;
  21. }
  22. } else {
  23. // handle milliseconds separately because of floating point math errors (issue #1867)
  24. days = this._days + Math.round(monthsToDays(this._months));
  25. switch (units) {
  26. case 'week':
  27. return days / 7 + milliseconds / 6048e5;
  28. case 'day':
  29. return days + milliseconds / 864e5;
  30. case 'hour':
  31. return days * 24 + milliseconds / 36e5;
  32. case 'minute':
  33. return days * 1440 + milliseconds / 6e4;
  34. case 'second':
  35. return days * 86400 + milliseconds / 1000;
  36. // Math.floor prevents floating point math errors here
  37. case 'millisecond':
  38. return Math.floor(days * 864e5) + milliseconds;
  39. default:
  40. throw new Error('Unknown unit ' + units);
  41. }
  42. }
  43. }
  44. function makeAs(alias) {
  45. return function () {
  46. return this.as(alias);
  47. };
  48. }
  49. var asMilliseconds = makeAs('ms'),
  50. asSeconds = makeAs('s'),
  51. asMinutes = makeAs('m'),
  52. asHours = makeAs('h'),
  53. asDays = makeAs('d'),
  54. asWeeks = makeAs('w'),
  55. asMonths = makeAs('M'),
  56. asQuarters = makeAs('Q'),
  57. asYears = makeAs('y'),
  58. valueOf = asMilliseconds;
  59. export {
  60. asMilliseconds,
  61. asSeconds,
  62. asMinutes,
  63. asHours,
  64. asDays,
  65. asWeeks,
  66. asMonths,
  67. asQuarters,
  68. asYears,
  69. valueOf,
  70. };