parseJSON.js 2.4 KB

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