isISO8601.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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)?)?)?)?$/;
  11. /* eslint-enable max-len */
  12. var isValidDate = function isValidDate(str) {
  13. // str must have passed the ISO8601 check
  14. // this check is meant to catch invalid dates
  15. // like 2009-02-31
  16. // first check for ordinal dates
  17. var ordinalMatch = str.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/);
  18. if (ordinalMatch) {
  19. var oYear = Number(ordinalMatch[1]);
  20. var oDay = Number(ordinalMatch[2]); // if is leap year
  21. if (oYear % 4 === 0 && oYear % 100 !== 0) return oDay <= 366;
  22. return oDay <= 365;
  23. }
  24. var match = str.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number);
  25. var year = match[1];
  26. var month = match[2];
  27. var day = match[3];
  28. var monthString = month ? "0".concat(month).slice(-2) : month;
  29. var dayString = day ? "0".concat(day).slice(-2) : day; // create a date object and compare
  30. var d = new Date("".concat(year, "-").concat(monthString || '01', "-").concat(dayString || '01'));
  31. if (isNaN(d.getUTCFullYear())) return false;
  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, options) {
  38. (0, _assertString.default)(str);
  39. var check = iso8601.test(str);
  40. if (!options) return check;
  41. if (check && options.strict) return isValidDate(str);
  42. return check;
  43. }
  44. module.exports = exports.default;
  45. module.exports.default = exports.default;