date-to-iso-string.js 1.8 KB

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