date-to-iso-string.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. var uncurryThis = require('../internals/function-uncurry-this');
  3. var fails = require('../internals/fails');
  4. var padStart = require('../internals/string-pad').start;
  5. var $RangeError = RangeError;
  6. var abs = Math.abs;
  7. var DatePrototype = Date.prototype;
  8. var n$DateToISOString = DatePrototype.toISOString;
  9. var getTime = uncurryThis(DatePrototype.getTime);
  10. var getUTCDate = uncurryThis(DatePrototype.getUTCDate);
  11. var getUTCFullYear = uncurryThis(DatePrototype.getUTCFullYear);
  12. var getUTCHours = uncurryThis(DatePrototype.getUTCHours);
  13. var getUTCMilliseconds = uncurryThis(DatePrototype.getUTCMilliseconds);
  14. var getUTCMinutes = uncurryThis(DatePrototype.getUTCMinutes);
  15. var getUTCMonth = uncurryThis(DatePrototype.getUTCMonth);
  16. var getUTCSeconds = uncurryThis(DatePrototype.getUTCSeconds);
  17. // `Date.prototype.toISOString` method implementation
  18. // https://tc39.es/ecma262/#sec-date.prototype.toisostring
  19. // PhantomJS / old WebKit fails here:
  20. module.exports = (fails(function () {
  21. return n$DateToISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
  22. }) || !fails(function () {
  23. n$DateToISOString.call(new Date(NaN));
  24. })) ? function toISOString() {
  25. if (!isFinite(getTime(this))) throw $RangeError('Invalid time value');
  26. var date = this;
  27. var year = getUTCFullYear(date);
  28. var milliseconds = getUTCMilliseconds(date);
  29. var sign = year < 0 ? '-' : year > 9999 ? '+' : '';
  30. return sign + padStart(abs(year), sign ? 6 : 4, 0) +
  31. '-' + padStart(getUTCMonth(date) + 1, 2, 0) +
  32. '-' + padStart(getUTCDate(date), 2, 0) +
  33. 'T' + padStart(getUTCHours(date), 2, 0) +
  34. ':' + padStart(getUTCMinutes(date), 2, 0) +
  35. ':' + padStart(getUTCSeconds(date), 2, 0) +
  36. '.' + padStart(milliseconds, 3, 0) +
  37. 'Z';
  38. } : n$DateToISOString;