-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (73 loc) · 2.27 KB
/
index.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
77
78
79
var formatDate = require('./formatDate.js');
function DateAny(format) {
if (!format) format = 'yyyy-MM-dd';
var regStr = format.replace(/([\-\\\?\(\)\{\}\[\]\^\$\+\.\*])/g, '\\$1'); //特殊符号转义
var group = {}, index = 1, reg;
regStr = regStr.replace(/(dd?|yyyy|yy|MM?|HH?|mm?|ss?)/g, function (m) {
switch (m) {
case 'd':
case 'dd':
group.day = index++;
return '(\\d{1,2})'
case 'yyyy':
case 'yy':
group.year = index++;
return '(\\d{' + m.length + '})'
case 'M':
case 'MM':
group.month = index++;
return '(\\d{1,2})'
case 'H':
case 'HH':
group.hour = index++;
return '(\\d{1,2})'
case 'm':
case 'mm':
group.minute = index++;
return '(\\d{1,2})'
case 's':
case 'ss':
group.second = index++;
return '(\\d{1,2})'
}
return m;
});
try {
reg = new RegExp(regStr);
} catch (e) {
reg = /^(\d{4}|\d{1,2})([-\/\.])(\d{1,2})\2(\d{1,2})$/;
group = { year: 1, month: 3, dat: 4 }
}
this.group = group;
this.check = function (str) {
var d = this.toDate(str);
if (d) {
var tx = this.format(d);
var dropPre0 = /\b0(\d)\b/g; //01和1要当成相等
return tx.replace(dropPre0, '$1') == str.replace(dropPre0, '$1');
}
return false
}
this.toDate = function (str) {
var m = reg.exec(str);
if (m) {
return initDate(m[group.year], m[group.month], m[group.day], m[group.hour], m[group.minute], m[group.second])
}
return null;
}
this.format = function (date) {
return formatDate(date, format)
}
}
function initDate(year, month, day, hour, minute, second) {
var d = new Date();
year = +year || d.getFullYear();
if (year < 100) year += 2000;
month = (+month || 1) - 1;
day = +day || 1;
hour = +hour || 0;
minute = +minute || 0;
second = +second || 0;
return new Date(year, month, day, hour, minute, second);
}
module.exports = DateAny;