isISO8601.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = isISO8601;
  6. var _assertString = _interopRequireDefault(require("./util/assertString"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8. /* eslint-disable max-len */
  9. // from http://goo.gl/0ejHHW
  10. 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
  11. 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)?)?)?)?$/;
  12. /* eslint-enable max-len */
  13. var isValidDate = function isValidDate(str) {
  14. // str must have passed the ISO8601 check
  15. // this check is meant to catch invalid dates
  16. // like 2009-02-31
  17. // first check for ordinal dates
  18. var ordinalMatch = str.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/);
  19. if (ordinalMatch) {
  20. var oYear = Number(ordinalMatch[1]);
  21. var oDay = Number(ordinalMatch[2]); // if is leap year
  22. if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366;
  23. return oDay <= 365;
  24. }
  25. var match = str.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number);
  26. var year = match[1];
  27. var month = match[2];
  28. var day = match[3];
  29. var monthString = month ? "0".concat(month).slice(-2) : month;
  30. var dayString = day ? "0".concat(day).slice(-2) : day; // create a date object and compare
  31. var d = new Date("".concat(year, "-").concat(monthString || '01', "-").concat(dayString || '01'));
  32. if (month && day) {
  33. return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day;
  34. }
  35. return true;
  36. };
  37. function isISO8601(str) {
  38. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  39. (0, _assertString.default)(str);
  40. var check = options.strictSeparator ? iso8601StrictSeparator.test(str) : iso8601.test(str);
  41. if (check && options.strict) return isValidDate(str);
  42. return check;
  43. }
  44. module.exports = exports.default;
  45. module.exports.default = exports.default;