PageRenderTime 16ms CodeModel.GetById 10ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/node_modules/moment/src/lib/duration/iso-string.js

https://bitbucket.org/coleman333/smartsite
JavaScript | 64 lines | 42 code | 10 blank | 12 comment | 5 complexity | 709938ee251f940e6fff2ff76111da19 MD5 | raw file
 1import absFloor from '../utils/abs-floor';
 2var abs = Math.abs;
 3
 4function sign(x) {
 5    return ((x > 0) - (x < 0)) || +x;
 6}
 7
 8export function toISOString() {
 9    // for ISO strings we do not use the normal bubbling rules:
10    //  * milliseconds bubble up until they become hours
11    //  * days do not bubble at all
12    //  * months bubble up until they become years
13    // This is because there is no context-free conversion between hours and days
14    // (think of clock changes)
15    // and also not between days and months (28-31 days per month)
16    if (!this.isValid()) {
17        return this.localeData().invalidDate();
18    }
19
20    var seconds = abs(this._milliseconds) / 1000;
21    var days         = abs(this._days);
22    var months       = abs(this._months);
23    var minutes, hours, years;
24
25    // 3600 seconds -> 60 minutes -> 1 hour
26    minutes           = absFloor(seconds / 60);
27    hours             = absFloor(minutes / 60);
28    seconds %= 60;
29    minutes %= 60;
30
31    // 12 months -> 1 year
32    years  = absFloor(months / 12);
33    months %= 12;
34
35
36    // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
37    var Y = years;
38    var M = months;
39    var D = days;
40    var h = hours;
41    var m = minutes;
42    var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
43    var total = this.asSeconds();
44
45    if (!total) {
46        // this is the same as C#'s (Noda) and python (isodate)...
47        // but not other JS (goog.date)
48        return 'P0D';
49    }
50
51    var totalSign = total < 0 ? '-' : '';
52    var ymSign = sign(this._months) !== sign(total) ? '-' : '';
53    var daysSign = sign(this._days) !== sign(total) ? '-' : '';
54    var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
55
56    return totalSign + 'P' +
57        (Y ? ymSign + Y + 'Y' : '') +
58        (M ? ymSign + M + 'M' : '') +
59        (D ? daysSign + D + 'D' : '') +
60        ((h || m || s) ? 'T' : '') +
61        (h ? hmsSign + h + 'H' : '') +
62        (m ? hmsSign + m + 'M' : '') +
63        (s ? hmsSign + s + 'S' : '');
64}