/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

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