parseJSON.mjs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @name parseJSON
  3. * @category Common Helpers
  4. * @summary Parse a JSON date string
  5. *
  6. * @description
  7. * Converts a complete ISO date string in UTC time, the typical format for transmitting
  8. * a date in JSON, to a JavaScript `Date` instance.
  9. *
  10. * This is a minimal implementation for converting dates retrieved from a JSON API to
  11. * a `Date` instance which can be used with other functions in the `date-fns` library.
  12. * The following formats are supported:
  13. *
  14. * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())`
  15. * - `2000-03-15T05:20:10Z`: Without milliseconds
  16. * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages
  17. * - `2000-03-15T05:20:10+05:45`: With a positive or negative offset, the default JSON encoded format in some other languages
  18. * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon
  19. * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol
  20. * - `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
  21. * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting
  22. *
  23. * For convenience and ease of use these other input types are also supported
  24. * via [toDate](https://date-fns.org/docs/toDate):
  25. *
  26. * - A `Date` instance will be cloned
  27. * - A `number` will be treated as a timestamp
  28. *
  29. * Any other input type or invalid date strings will return an `Invalid Date`.
  30. *
  31. * @param dateStr - A fully formed ISO8601 date string to convert
  32. *
  33. * @returns The parsed date in the local time zone
  34. */
  35. export function parseJSON(dateStr) {
  36. const parts = dateStr.match(
  37. /(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|(.)(\d{2}):?(\d{2})?)?/,
  38. );
  39. if (parts) {
  40. // Group 8 matches the sign
  41. return new Date(
  42. Date.UTC(
  43. +parts[1],
  44. +parts[2] - 1,
  45. +parts[3],
  46. +parts[4] - (+parts[9] || 0) * (parts[8] == "-" ? -1 : 1),
  47. +parts[5] - (+parts[10] || 0) * (parts[8] == "-" ? -1 : 1),
  48. +parts[6],
  49. +((parts[7] || "0") + "00").substring(0, 3),
  50. ),
  51. );
  52. }
  53. return new Date(NaN);
  54. }
  55. // Fallback for modularized imports:
  56. export default parseJSON;