d05bce92e212ce66b22e150d048a2de65cb0599c745a480d5e739187a4763c5f19f25747635df1ae57b65eb9c5817f841b32d49597acab09f5326c86ef948c 1.5 KB

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