formatISO.mjs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { toDate } from "./toDate.mjs";
  2. import { addLeadingZeros } from "./_lib/addLeadingZeros.mjs";
  3. /**
  4. * The {@link formatISO} function options.
  5. */
  6. /**
  7. * @name formatISO
  8. * @category Common Helpers
  9. * @summary Format the date according to the ISO 8601 standard (https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm).
  10. *
  11. * @description
  12. * Return the formatted date string in ISO 8601 format. Options may be passed to control the parts and notations of the date.
  13. *
  14. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  15. *
  16. * @param date - The original date
  17. * @param options - An object with options.
  18. *
  19. * @returns The formatted date string (in loca.l time zone)
  20. *
  21. * @throws `date` must not be Invalid Date
  22. *
  23. * @example
  24. * // Represent 18 September 2019 in ISO 8601 format (local time zone is UTC):
  25. * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52))
  26. * //=> '2019-09-18T19:00:52Z'
  27. *
  28. * @example
  29. * // Represent 18 September 2019 in ISO 8601, short format (local time zone is UTC):
  30. * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })
  31. * //=> '20190918T190052'
  32. *
  33. * @example
  34. * // Represent 18 September 2019 in ISO 8601 format, date only:
  35. * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })
  36. * //=> '2019-09-18'
  37. *
  38. * @example
  39. * // Represent 18 September 2019 in ISO 8601 format, time only (local time zone is UTC):
  40. * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })
  41. * //=> '19:00:52Z'
  42. */
  43. export function formatISO(date, options) {
  44. const _date = toDate(date);
  45. if (isNaN(_date.getTime())) {
  46. throw new RangeError("Invalid time value");
  47. }
  48. const format = options?.format ?? "extended";
  49. const representation = options?.representation ?? "complete";
  50. let result = "";
  51. let tzOffset = "";
  52. const dateDelimiter = format === "extended" ? "-" : "";
  53. const timeDelimiter = format === "extended" ? ":" : "";
  54. // Representation is either 'date' or 'complete'
  55. if (representation !== "time") {
  56. const day = addLeadingZeros(_date.getDate(), 2);
  57. const month = addLeadingZeros(_date.getMonth() + 1, 2);
  58. const year = addLeadingZeros(_date.getFullYear(), 4);
  59. // yyyyMMdd or yyyy-MM-dd.
  60. result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;
  61. }
  62. // Representation is either 'time' or 'complete'
  63. if (representation !== "date") {
  64. // Add the timezone.
  65. const offset = _date.getTimezoneOffset();
  66. if (offset !== 0) {
  67. const absoluteOffset = Math.abs(offset);
  68. const hourOffset = addLeadingZeros(Math.trunc(absoluteOffset / 60), 2);
  69. const minuteOffset = addLeadingZeros(absoluteOffset % 60, 2);
  70. // If less than 0, the sign is +, because it is ahead of time.
  71. const sign = offset < 0 ? "+" : "-";
  72. tzOffset = `${sign}${hourOffset}:${minuteOffset}`;
  73. } else {
  74. tzOffset = "Z";
  75. }
  76. const hour = addLeadingZeros(_date.getHours(), 2);
  77. const minute = addLeadingZeros(_date.getMinutes(), 2);
  78. const second = addLeadingZeros(_date.getSeconds(), 2);
  79. // If there's also date, separate it with time with 'T'
  80. const separator = result === "" ? "" : "T";
  81. // Creates a time string consisting of hour, minute, and second, separated by delimiters, if defined.
  82. const time = [hour, minute, second].join(timeDelimiter);
  83. // HHmmss or HH:mm:ss.
  84. result = `${result}${separator}${time}${tzOffset}`;
  85. }
  86. return result;
  87. }
  88. // Fallback for modularized imports:
  89. export default formatISO;