parseISO.cjs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. "use strict";
  2. exports.parseISO = parseISO;
  3. var _index = require("./constants.cjs");
  4. var _index2 = require("./constructFrom.cjs");
  5. var _index3 = require("./toDate.cjs");
  6. /**
  7. * The {@link parseISO} function options.
  8. */
  9. /**
  10. * @name parseISO
  11. * @category Common Helpers
  12. * @summary Parse ISO string
  13. *
  14. * @description
  15. * Parse the given string in ISO 8601 format and return an instance of Date.
  16. *
  17. * Function accepts complete ISO 8601 formats as well as partial implementations.
  18. * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601
  19. *
  20. * If the argument isn't a string, the function cannot parse the string or
  21. * the values are invalid, it returns Invalid Date.
  22. *
  23. * @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).
  24. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  25. *
  26. * @param argument - The value to convert
  27. * @param options - An object with options
  28. *
  29. * @returns The parsed date in the local time zone
  30. *
  31. * @example
  32. * // Convert string '2014-02-11T11:30:30' to date:
  33. * const result = parseISO('2014-02-11T11:30:30')
  34. * //=> Tue Feb 11 2014 11:30:30
  35. *
  36. * @example
  37. * // Convert string '+02014101' to date,
  38. * // if the additional number of digits in the extended year format is 1:
  39. * const result = parseISO('+02014101', { additionalDigits: 1 })
  40. * //=> Fri Apr 11 2014 00:00:00
  41. */
  42. function parseISO(argument, options) {
  43. const invalidDate = () => (0, _index2.constructFrom)(options?.in, NaN);
  44. const additionalDigits = options?.additionalDigits ?? 2;
  45. const dateStrings = splitDateString(argument);
  46. let date;
  47. if (dateStrings.date) {
  48. const parseYearResult = parseYear(dateStrings.date, additionalDigits);
  49. date = parseDate(parseYearResult.restDateString, parseYearResult.year);
  50. }
  51. if (!date || isNaN(+date)) return invalidDate();
  52. const timestamp = +date;
  53. let time = 0;
  54. let offset;
  55. if (dateStrings.time) {
  56. time = parseTime(dateStrings.time);
  57. if (isNaN(time)) return invalidDate();
  58. }
  59. if (dateStrings.timezone) {
  60. offset = parseTimezone(dateStrings.timezone);
  61. if (isNaN(offset)) return invalidDate();
  62. } else {
  63. const tmpDate = new Date(timestamp + time);
  64. const result = (0, _index3.toDate)(0, options?.in);
  65. result.setFullYear(
  66. tmpDate.getUTCFullYear(),
  67. tmpDate.getUTCMonth(),
  68. tmpDate.getUTCDate(),
  69. );
  70. result.setHours(
  71. tmpDate.getUTCHours(),
  72. tmpDate.getUTCMinutes(),
  73. tmpDate.getUTCSeconds(),
  74. tmpDate.getUTCMilliseconds(),
  75. );
  76. return result;
  77. }
  78. return (0, _index3.toDate)(timestamp + time + offset, options?.in);
  79. }
  80. const patterns = {
  81. dateTimeDelimiter: /[T ]/,
  82. timeZoneDelimiter: /[Z ]/i,
  83. timezone: /([Z+-].*)$/,
  84. };
  85. const dateRegex =
  86. /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
  87. const timeRegex =
  88. /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
  89. const timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
  90. function splitDateString(dateString) {
  91. const dateStrings = {};
  92. const array = dateString.split(patterns.dateTimeDelimiter);
  93. let timeString;
  94. // The regex match should only return at maximum two array elements.
  95. // [date], [time], or [date, time].
  96. if (array.length > 2) {
  97. return dateStrings;
  98. }
  99. if (/:/.test(array[0])) {
  100. timeString = array[0];
  101. } else {
  102. dateStrings.date = array[0];
  103. timeString = array[1];
  104. if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
  105. dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
  106. timeString = dateString.substr(
  107. dateStrings.date.length,
  108. dateString.length,
  109. );
  110. }
  111. }
  112. if (timeString) {
  113. const token = patterns.timezone.exec(timeString);
  114. if (token) {
  115. dateStrings.time = timeString.replace(token[1], "");
  116. dateStrings.timezone = token[1];
  117. } else {
  118. dateStrings.time = timeString;
  119. }
  120. }
  121. return dateStrings;
  122. }
  123. function parseYear(dateString, additionalDigits) {
  124. const regex = new RegExp(
  125. "^(?:(\\d{4}|[+-]\\d{" +
  126. (4 + additionalDigits) +
  127. "})|(\\d{2}|[+-]\\d{" +
  128. (2 + additionalDigits) +
  129. "})$)",
  130. );
  131. const captures = dateString.match(regex);
  132. // Invalid ISO-formatted year
  133. if (!captures) return { year: NaN, restDateString: "" };
  134. const year = captures[1] ? parseInt(captures[1]) : null;
  135. const century = captures[2] ? parseInt(captures[2]) : null;
  136. // either year or century is null, not both
  137. return {
  138. year: century === null ? year : century * 100,
  139. restDateString: dateString.slice((captures[1] || captures[2]).length),
  140. };
  141. }
  142. function parseDate(dateString, year) {
  143. // Invalid ISO-formatted year
  144. if (year === null) return new Date(NaN);
  145. const captures = dateString.match(dateRegex);
  146. // Invalid ISO-formatted string
  147. if (!captures) return new Date(NaN);
  148. const isWeekDate = !!captures[4];
  149. const dayOfYear = parseDateUnit(captures[1]);
  150. const month = parseDateUnit(captures[2]) - 1;
  151. const day = parseDateUnit(captures[3]);
  152. const week = parseDateUnit(captures[4]);
  153. const dayOfWeek = parseDateUnit(captures[5]) - 1;
  154. if (isWeekDate) {
  155. if (!validateWeekDate(year, week, dayOfWeek)) {
  156. return new Date(NaN);
  157. }
  158. return dayOfISOWeekYear(year, week, dayOfWeek);
  159. } else {
  160. const date = new Date(0);
  161. if (
  162. !validateDate(year, month, day) ||
  163. !validateDayOfYearDate(year, dayOfYear)
  164. ) {
  165. return new Date(NaN);
  166. }
  167. date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
  168. return date;
  169. }
  170. }
  171. function parseDateUnit(value) {
  172. return value ? parseInt(value) : 1;
  173. }
  174. function parseTime(timeString) {
  175. const captures = timeString.match(timeRegex);
  176. if (!captures) return NaN; // Invalid ISO-formatted time
  177. const hours = parseTimeUnit(captures[1]);
  178. const minutes = parseTimeUnit(captures[2]);
  179. const seconds = parseTimeUnit(captures[3]);
  180. if (!validateTime(hours, minutes, seconds)) {
  181. return NaN;
  182. }
  183. return (
  184. hours * _index.millisecondsInHour +
  185. minutes * _index.millisecondsInMinute +
  186. seconds * 1000
  187. );
  188. }
  189. function parseTimeUnit(value) {
  190. return (value && parseFloat(value.replace(",", "."))) || 0;
  191. }
  192. function parseTimezone(timezoneString) {
  193. if (timezoneString === "Z") return 0;
  194. const captures = timezoneString.match(timezoneRegex);
  195. if (!captures) return 0;
  196. const sign = captures[1] === "+" ? -1 : 1;
  197. const hours = parseInt(captures[2]);
  198. const minutes = (captures[3] && parseInt(captures[3])) || 0;
  199. if (!validateTimezone(hours, minutes)) {
  200. return NaN;
  201. }
  202. return (
  203. sign *
  204. (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute)
  205. );
  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. }