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