index.js 8.9 KB

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