isISO8601.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import assertString from './util/assertString';
  2. /* eslint-disable max-len */
  3. // from http://goo.gl/0ejHHW
  4. var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; // same as above, except with a strict 'T' separator between date and time
  5. var iso8601StrictSeparator = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
  6. /* eslint-enable max-len */
  7. var isValidDate = function isValidDate(str) {
  8. // str must have passed the ISO8601 check
  9. // this check is meant to catch invalid dates
  10. // like 2009-02-31
  11. // first check for ordinal dates
  12. var ordinalMatch = str.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/);
  13. if (ordinalMatch) {
  14. var oYear = Number(ordinalMatch[1]);
  15. var oDay = Number(ordinalMatch[2]); // if is leap year
  16. if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366;
  17. return oDay <= 365;
  18. }
  19. var match = str.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number);
  20. var year = match[1];
  21. var month = match[2];
  22. var day = match[3];
  23. var monthString = month ? "0".concat(month).slice(-2) : month;
  24. var dayString = day ? "0".concat(day).slice(-2) : day; // create a date object and compare
  25. var d = new Date("".concat(year, "-").concat(monthString || '01', "-").concat(dayString || '01'));
  26. if (month && day) {
  27. return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day;
  28. }
  29. return true;
  30. };
  31. export default function isISO8601(str) {
  32. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  33. assertString(str);
  34. var check = options.strictSeparator ? iso8601StrictSeparator.test(str) : iso8601.test(str);
  35. if (check && options.strict) return isValidDate(str);
  36. return check;
  37. }