Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

298 строки
9.0 KiB

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