-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
isDate.js
76 lines (60 loc) · 2.1 KB
/
isDate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import merge from './util/merge';
const default_date_options = {
format: 'YYYY/MM/DD',
delimiters: ['/', '-'],
strictMode: false,
};
function isValidFormat(format) {
return /(^(y{4}|y{2})[.\/-](m{1,2})[.\/-](d{1,2})$)|(^(m{1,2})[.\/-](d{1,2})[.\/-]((y{4}|y{2})$))|(^(d{1,2})[.\/-](m{1,2})[.\/-]((y{4}|y{2})$))/gi.test(format);
}
function zip(date, format) {
const zippedArr = [],
len = Math.min(date.length, format.length);
for (let i = 0; i < len; i++) {
zippedArr.push([date[i], format[i]]);
}
return zippedArr;
}
export default function isDate(input, options) {
if (typeof options === 'string') { // Allow backward compatbility for old format isDate(input [, format])
options = merge({ format: options }, default_date_options);
} else {
options = merge(options, default_date_options);
}
if (typeof input === 'string' && isValidFormat(options.format)) {
const formatDelimiter = options.delimiters
.find(delimiter => options.format.indexOf(delimiter) !== -1);
const dateDelimiter = options.strictMode
? formatDelimiter
: options.delimiters.find(delimiter => input.indexOf(delimiter) !== -1);
const dateAndFormat = zip(
input.split(dateDelimiter),
options.format.toLowerCase().split(formatDelimiter)
);
const dateObj = {};
for (const [dateWord, formatWord] of dateAndFormat) {
if (dateWord.length !== formatWord.length) {
return false;
}
dateObj[formatWord.charAt(0)] = dateWord;
}
let fullYear = dateObj.y;
if (dateObj.y.length === 2) {
const parsedYear = parseInt(dateObj.y, 10);
if (isNaN(parsedYear)) {
return false;
}
const currentYearLastTwoDigits = new Date().getFullYear() % 100;
if (parsedYear < currentYearLastTwoDigits) {
fullYear = `20${dateObj.y}`;
} else {
fullYear = `19${dateObj.y}`;
}
}
return new Date(`${fullYear}-${dateObj.m}-${dateObj.d}`).getDate() === +dateObj.d;
}
if (!options.strictMode) {
return Object.prototype.toString.call(input) === '[object Date]' && isFinite(input);
}
return false;
}