parseISO.mjs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { millisecondsInHour, millisecondsInMinute } from "./constants.mjs";
  2. /**
  3. * The {@link parseISO} function options.
  4. */
  5. /**
  6. * @name parseISO
  7. * @category Common Helpers
  8. * @summary Parse ISO string
  9. *
  10. * @description
  11. * Parse the given string in ISO 8601 format and return an instance of Date.
  12. *
  13. * Function accepts complete ISO 8601 formats as well as partial implementations.
  14. * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601
  15. *
  16. * If the argument isn't a string, the function cannot parse the string or
  17. * the values are invalid, it returns Invalid Date.
  18. *
  19. * @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).
  20. *
  21. * @param argument - The value to convert
  22. * @param options - An object with options
  23. *
  24. * @returns The parsed date in the local time zone
  25. *
  26. * @example
  27. * // Convert string '2014-02-11T11:30:30' to date:
  28. * const result = parseISO('2014-02-11T11:30:30')
  29. * //=> Tue Feb 11 2014 11:30:30
  30. *
  31. * @example
  32. * // Convert string '+02014101' to date,
  33. * // if the additional number of digits in the extended year format is 1:
  34. * const result = parseISO('+02014101', { additionalDigits: 1 })
  35. * //=> Fri Apr 11 2014 00:00:00
  36. */
  37. export function parseISO(argument, options) {
  38. const additionalDigits = options?.additionalDigits ?? 2;
  39. const dateStrings = splitDateString(argument);
  40. let date;
  41. if (dateStrings.date) {
  42. const parseYearResult = parseYear(dateStrings.date, additionalDigits);
  43. date = parseDate(parseYearResult.restDateString, parseYearResult.year);
  44. }
  45. if (!date || isNaN(date.getTime())) {
  46. return new Date(NaN);
  47. }
  48. const timestamp = date.getTime();
  49. let time = 0;
  50. let offset;
  51. if (dateStrings.time) {
  52. time = parseTime(dateStrings.time);
  53. if (isNaN(time)) {
  54. return new Date(NaN);
  55. }
  56. }
  57. if (dateStrings.timezone) {
  58. offset = parseTimezone(dateStrings.timezone);
  59. if (isNaN(offset)) {
  60. return new Date(NaN);
  61. }
  62. } else {
  63. const dirtyDate = new Date(timestamp + time);
  64. // JS parsed string assuming it's in UTC timezone
  65. // but we need it to be parsed in our timezone
  66. // so we use utc values to build date in our timezone.
  67. // Year values from 0 to 99 map to the years 1900 to 1999
  68. // so set year explicitly with setFullYear.
  69. const result = new Date(0);
  70. result.setFullYear(
  71. dirtyDate.getUTCFullYear(),
  72. dirtyDate.getUTCMonth(),
  73. dirtyDate.getUTCDate(),
  74. );
  75. result.setHours(
  76. dirtyDate.getUTCHours(),
  77. dirtyDate.getUTCMinutes(),
  78. dirtyDate.getUTCSeconds(),
  79. dirtyDate.getUTCMilliseconds(),
  80. );
  81. return result;
  82. }
  83. return new Date(timestamp + time + offset);
  84. }
  85. const patterns = {
  86. dateTimeDelimiter: /[T ]/,
  87. timeZoneDelimiter: /[Z ]/i,
  88. timezone: /([Z+-].*)$/,
  89. };
  90. const dateRegex =
  91. /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
  92. const timeRegex =
  93. /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
  94. const timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
  95. function splitDateString(dateString) {
  96. const dateStrings = {};
  97. const array = dateString.split(patterns.dateTimeDelimiter);
  98. let timeString;
  99. // The regex match should only return at maximum two array elements.
  100. // [date], [time], or [date, time].
  101. if (array.length > 2) {
  102. return dateStrings;
  103. }
  104. if (/:/.test(array[0])) {
  105. timeString = array[0];
  106. } else {
  107. dateStrings.date = array[0];
  108. timeString = array[1];
  109. if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
  110. dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
  111. timeString = dateString.substr(
  112. dateStrings.date.length,
  113. dateString.length,
  114. );
  115. }
  116. }
  117. if (timeString) {
  118. const token = patterns.timezone.exec(timeString);
  119. if (token) {
  120. dateStrings.time = timeString.replace(token[1], "");
  121. dateStrings.timezone = token[1];
  122. } else {
  123. dateStrings.time = timeString;
  124. }
  125. }
  126. return dateStrings;
  127. }
  128. function parseYear(dateString, additionalDigits) {
  129. const regex = new RegExp(
  130. "^(?:(\\d{4}|[+-]\\d{" +
  131. (4 + additionalDigits) +
  132. "})|(\\d{2}|[+-]\\d{" +
  133. (2 + additionalDigits) +
  134. "})$)",
  135. );
  136. const captures = dateString.match(regex);
  137. // Invalid ISO-formatted year
  138. if (!captures) return { year: NaN, restDateString: "" };
  139. const year = captures[1] ? parseInt(captures[1]) : null;
  140. const century = captures[2] ? parseInt(captures[2]) : null;
  141. // either year or century is null, not both
  142. return {
  143. year: century === null ? year : century * 100,
  144. restDateString: dateString.slice((captures[1] || captures[2]).length),
  145. };
  146. }
  147. function parseDate(dateString, year) {
  148. // Invalid ISO-formatted year
  149. if (year === null) return new Date(NaN);
  150. const captures = dateString.match(dateRegex);
  151. // Invalid ISO-formatted string
  152. if (!captures) return new Date(NaN);
  153. const isWeekDate = !!captures[4];
  154. const dayOfYear = parseDateUnit(captures[1]);
  155. const month = parseDateUnit(captures[2]) - 1;
  156. const day = parseDateUnit(captures[3]);
  157. const week = parseDateUnit(captures[4]);
  158. const dayOfWeek = parseDateUnit(captures[5]) - 1;
  159. if (isWeekDate) {
  160. if (!validateWeekDate(year, week, dayOfWeek)) {
  161. return new Date(NaN);
  162. }
  163. return dayOfISOWeekYear(year, week, dayOfWeek);
  164. } else {
  165. const date = new Date(0);
  166. if (
  167. !validateDate(year, month, day) ||
  168. !validateDayOfYearDate(year, dayOfYear)
  169. ) {
  170. return new Date(NaN);
  171. }
  172. date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
  173. return date;
  174. }
  175. }
  176. function parseDateUnit(value) {
  177. return value ? parseInt(value) : 1;
  178. }
  179. function parseTime(timeString) {
  180. const captures = timeString.match(timeRegex);
  181. if (!captures) return NaN; // Invalid ISO-formatted time
  182. const hours = parseTimeUnit(captures[1]);
  183. const minutes = parseTimeUnit(captures[2]);
  184. const seconds = parseTimeUnit(captures[3]);
  185. if (!validateTime(hours, minutes, seconds)) {
  186. return NaN;
  187. }
  188. return (
  189. hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1000
  190. );
  191. }
  192. function parseTimeUnit(value) {
  193. return (value && parseFloat(value.replace(",", "."))) || 0;
  194. }
  195. function parseTimezone(timezoneString) {
  196. if (timezoneString === "Z") return 0;
  197. const captures = timezoneString.match(timezoneRegex);
  198. if (!captures) return 0;
  199. const sign = captures[1] === "+" ? -1 : 1;
  200. const hours = parseInt(captures[2]);
  201. const minutes = (captures[3] && parseInt(captures[3])) || 0;
  202. if (!validateTimezone(hours, minutes)) {
  203. return NaN;
  204. }
  205. return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute);
  206. }
  207. function dayOfISOWeekYear(isoWeekYear, week, day) {
  208. const date = new Date(0);
  209. date.setUTCFullYear(isoWeekYear, 0, 4);
  210. const fourthOfJanuaryDay = date.getUTCDay() || 7;
  211. const diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
  212. date.setUTCDate(date.getUTCDate() + diff);
  213. return date;
  214. }
  215. // Validation functions
  216. // February is null to handle the leap year (using ||)
  217. const daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  218. function isLeapYearIndex(year) {
  219. return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
  220. }
  221. function validateDate(year, month, date) {
  222. return (
  223. month >= 0 &&
  224. month <= 11 &&
  225. date >= 1 &&
  226. date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28))
  227. );
  228. }
  229. function validateDayOfYearDate(year, dayOfYear) {
  230. return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
  231. }
  232. function validateWeekDate(_year, week, day) {
  233. return week >= 1 && week <= 53 && day >= 0 && day <= 6;
  234. }
  235. function validateTime(hours, minutes, seconds) {
  236. if (hours === 24) {
  237. return minutes === 0 && seconds === 0;
  238. }
  239. return (
  240. seconds >= 0 &&
  241. seconds < 60 &&
  242. minutes >= 0 &&
  243. minutes < 60 &&
  244. hours >= 0 &&
  245. hours < 25
  246. );
  247. }
  248. function validateTimezone(_hours, minutes) {
  249. return minutes >= 0 && minutes <= 59;
  250. }
  251. // Fallback for modularized imports:
  252. export default parseISO;