date-to-iso-string.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 $isFinite = isFinite;
  7. var abs = Math.abs;
  8. var DatePrototype = Date.prototype;
  9. var nativeDateToISOString = DatePrototype.toISOString;
  10. var thisTimeValue = 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 nativeDateToISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
  23. }) || !fails(function () {
  24. nativeDateToISOString.call(new Date(NaN));
  25. })) ? function toISOString() {
  26. if (!$isFinite(thisTimeValue(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. } : nativeDateToISOString;