as.js 2.3 KB

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