Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

před 3 roky
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = parseJSON;
  6. var _index = _interopRequireDefault(require("../toDate/index.js"));
  7. var _index2 = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. /**
  10. * @name parseJSON
  11. * @category Common Helpers
  12. * @summary Parse a JSON date string
  13. *
  14. * @description
  15. * Converts a complete ISO date string in UTC time, the typical format for transmitting
  16. * a date in JSON, to a JavaScript `Date` instance.
  17. *
  18. * This is a minimal implementation for converting dates retrieved from a JSON API to
  19. * a `Date` instance which can be used with other functions in the `date-fns` library.
  20. * The following formats are supported:
  21. *
  22. * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())`
  23. * - `2000-03-15T05:20:10Z`: Without milliseconds
  24. * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages
  25. * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon
  26. * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol
  27. * - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds
  28. * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting
  29. *
  30. * For convenience and ease of use these other input types are also supported
  31. * via [toDate]{@link https://date-fns.org/docs/toDate}:
  32. *
  33. * - A `Date` instance will be cloned
  34. * - A `number` will be treated as a timestamp
  35. *
  36. * Any other input type or invalid date strings will return an `Invalid Date`.
  37. *
  38. * @param {String|Number|Date} argument A fully formed ISO8601 date string to convert
  39. * @returns {Date} the parsed date in the local time zone
  40. * @throws {TypeError} 1 argument required
  41. */
  42. function parseJSON(argument) {
  43. (0, _index2.default)(1, arguments);
  44. if (typeof argument === 'string') {
  45. var parts = argument.match(/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|\+00:?00)?/);
  46. if (parts) {
  47. return new Date(Date.UTC(+parts[1], parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6], +((parts[7] || '0') + '00').substring(0, 3)));
  48. }
  49. return new Date(NaN);
  50. }
  51. return (0, _index.default)(argument);
  52. }
  53. module.exports = exports.default;