Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

331 lines
11 KiB

4 years ago
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import defaultLocale from './locale/en';
import { startOfWeekYear } from './util';
var formattingTokens = /(\[[^\[]*\])|(MM?M?M?|Do|DD?|ddd?d?|w[o|w]?|YYYY|YY|a|A|hh?|HH?|mm?|ss?|S{1,3}|x|X|ZZ?|.)/g;
var match1 = /\d/; // 0 - 9
var match2 = /\d\d/; // 00 - 99
var match3 = /\d{3}/; // 000 - 999
var match4 = /\d{4}/; // 0000 - 9999
var match1to2 = /\d\d?/; // 0 - 99
var matchShortOffset = /[+-]\d\d:?\d\d/; // +00:00 -00:00 +0000 or -0000
var matchSigned = /[+-]?\d+/; // -inf - inf
var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
// const matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; // Word
var YEAR = 'year';
var MONTH = 'month';
var DAY = 'day';
var HOUR = 'hour';
var MINUTE = 'minute';
var SECOND = 'second';
var MILLISECOND = 'millisecond';
var parseFlags = {};
var addParseFlag = function addParseFlag(token, regex, callback) {
var tokens = Array.isArray(token) ? token : [token];
var func;
if (typeof callback === 'string') {
func = function func(input) {
var value = parseInt(input, 10);
return _defineProperty({}, callback, value);
};
} else {
func = callback;
}
tokens.forEach(function (key) {
parseFlags[key] = [regex, func];
});
};
var escapeStringRegExp = function escapeStringRegExp(str) {
return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
};
var matchWordRegExp = function matchWordRegExp(localeKey) {
return function (locale) {
var array = locale[localeKey];
if (!Array.isArray(array)) {
throw new Error("Locale[".concat(localeKey, "] need an array"));
}
return new RegExp(array.map(escapeStringRegExp).join('|'));
};
};
var matchWordCallback = function matchWordCallback(localeKey, key) {
return function (input, locale) {
var array = locale[localeKey];
if (!Array.isArray(array)) {
throw new Error("Locale[".concat(localeKey, "] need an array"));
}
var index = array.indexOf(input);
if (index < 0) {
throw new Error('Invalid Word');
}
return _defineProperty({}, key, index);
};
};
addParseFlag('Y', matchSigned, YEAR);
addParseFlag('YY', match2, function (input) {
var year = new Date().getFullYear();
var cent = Math.floor(year / 100);
var value = parseInt(input, 10);
value = (value > 68 ? cent - 1 : cent) * 100 + value;
return _defineProperty({}, YEAR, value);
});
addParseFlag('YYYY', match4, YEAR);
addParseFlag('M', match1to2, function (input) {
return _defineProperty({}, MONTH, parseInt(input, 10) - 1);
});
addParseFlag('MM', match2, function (input) {
return _defineProperty({}, MONTH, parseInt(input, 10) - 1);
});
addParseFlag('MMM', matchWordRegExp('monthsShort'), matchWordCallback('monthsShort', MONTH));
addParseFlag('MMMM', matchWordRegExp('months'), matchWordCallback('months', MONTH));
addParseFlag('D', match1to2, DAY);
addParseFlag('DD', match2, DAY);
addParseFlag(['H', 'h'], match1to2, HOUR);
addParseFlag(['HH', 'hh'], match2, HOUR);
addParseFlag('m', match1to2, MINUTE);
addParseFlag('mm', match2, MINUTE);
addParseFlag('s', match1to2, SECOND);
addParseFlag('ss', match2, SECOND);
addParseFlag('S', match1, function (input) {
return _defineProperty({}, MILLISECOND, parseInt(input, 10) * 100);
});
addParseFlag('SS', match2, function (input) {
return _defineProperty({}, MILLISECOND, parseInt(input, 10) * 10);
});
addParseFlag('SSS', match3, MILLISECOND);
function matchMeridiem(locale) {
return locale.meridiemParse || /[ap]\.?m?\.?/i;
}
function defaultIsPM(input) {
return "".concat(input).toLowerCase().charAt(0) === 'p';
}
addParseFlag(['A', 'a'], matchMeridiem, function (input, locale) {
var isPM = typeof locale.isPM === 'function' ? locale.isPM(input) : defaultIsPM(input);
return {
isPM: isPM
};
});
function offsetFromString(str) {
var _ref8 = str.match(/([+-]|\d\d)/g) || ['-', '0', '0'],
_ref9 = _slicedToArray(_ref8, 3),
symbol = _ref9[0],
hour = _ref9[1],
minute = _ref9[2];
var minutes = parseInt(hour, 10) * 60 + parseInt(minute, 10);
if (minutes === 0) {
return 0;
}
return symbol === '+' ? -minutes : +minutes;
}
addParseFlag(['Z', 'ZZ'], matchShortOffset, function (input) {
return {
offset: offsetFromString(input)
};
});
addParseFlag('x', matchSigned, function (input) {
return {
date: new Date(parseInt(input, 10))
};
});
addParseFlag('X', matchTimestamp, function (input) {
return {
date: new Date(parseFloat(input) * 1000)
};
});
addParseFlag('d', match1, 'weekday');
addParseFlag('dd', matchWordRegExp('weekdaysMin'), matchWordCallback('weekdaysMin', 'weekday'));
addParseFlag('ddd', matchWordRegExp('weekdaysShort'), matchWordCallback('weekdaysShort', 'weekday'));
addParseFlag('dddd', matchWordRegExp('weekdays'), matchWordCallback('weekdays', 'weekday'));
addParseFlag('w', match1to2, 'week');
addParseFlag('ww', match2, 'week');
function to24hour(hour, isPM) {
if (hour !== undefined && isPM !== undefined) {
if (isPM) {
if (hour < 12) {
return hour + 12;
}
} else if (hour === 12) {
return 0;
}
}
return hour;
}
function getFullInputArray(input) {
var backupDate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date();
var result = [0, 0, 1, 0, 0, 0, 0];
var backupArr = [backupDate.getFullYear(), backupDate.getMonth(), backupDate.getDate(), backupDate.getHours(), backupDate.getMinutes(), backupDate.getSeconds(), backupDate.getMilliseconds()];
var useBackup = true;
for (var i = 0; i < 7; i++) {
if (input[i] === undefined) {
result[i] = useBackup ? backupArr[i] : result[i];
} else {
result[i] = input[i];
useBackup = false;
}
}
return result;
}
function createUTCDate() {
var date;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var y = args[0];
if (y < 100 && y >= 0) {
args[0] += 400;
date = new Date(Date.UTC.apply(Date, args)); // eslint-disable-next-line no-restricted-globals
if (isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
} else {
date = new Date(Date.UTC.apply(Date, args));
}
return date;
}
function makeParser(dateString, format, locale) {
var tokens = format.match(formattingTokens);
if (!tokens) {
throw new Error();
}
var length = tokens.length;
var mark = {};
for (var i = 0; i < length; i += 1) {
var token = tokens[i];
var parseTo = parseFlags[token];
if (!parseTo) {
var word = token.replace(/^\[|\]$/g, '');
if (dateString.indexOf(word) === 0) {
dateString = dateString.substr(word.length);
} else {
throw new Error('not match');
}
} else {
var regex = typeof parseTo[0] === 'function' ? parseTo[0](locale) : parseTo[0];
var parser = parseTo[1];
var value = (regex.exec(dateString) || [])[0];
var obj = parser(value, locale);
mark = _objectSpread({}, mark, {}, obj);
dateString = dateString.replace(value, '');
}
}
return mark;
}
export default function parse(str, format) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
try {
var _options$locale = options.locale,
_locale = _options$locale === void 0 ? defaultLocale : _options$locale,
_options$backupDate = options.backupDate,
backupDate = _options$backupDate === void 0 ? new Date() : _options$backupDate;
var parseResult = makeParser(str, format, _locale);
var year = parseResult.year,
month = parseResult.month,
day = parseResult.day,
hour = parseResult.hour,
minute = parseResult.minute,
second = parseResult.second,
millisecond = parseResult.millisecond,
isPM = parseResult.isPM,
date = parseResult.date,
offset = parseResult.offset,
weekday = parseResult.weekday,
week = parseResult.week;
if (date) {
return date;
}
var inputArray = [year, month, day, hour, minute, second, millisecond];
inputArray[3] = to24hour(inputArray[3], isPM); // check week
if (week !== undefined && month === undefined && day === undefined) {
// new Date(year, 3) make sure in current year
var firstDate = startOfWeekYear(year === undefined ? backupDate : new Date(year, 3), {
firstDayOfWeek: _locale.firstDayOfWeek,
firstWeekContainsDate: _locale.firstWeekContainsDate
});
return new Date(firstDate.getTime() + (week - 1) * 7 * 24 * 3600 * 1000);
}
var utcDate = createUTCDate.apply(void 0, _toConsumableArray(getFullInputArray(inputArray, backupDate)));
var offsetMilliseconds = (offset === undefined ? utcDate.getTimezoneOffset() : offset) * 60 * 1000;
var parsedDate = new Date(utcDate.getTime() + offsetMilliseconds); // check weekday
if (weekday !== undefined && parsedDate.getDay() !== weekday) {
return new Date(NaN);
}
return parsedDate;
} catch (e) {
return new Date(NaN);
}
}