-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstringdate.js
72 lines (57 loc) · 1.82 KB
/
stringdate.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
/*
* String-Date JavaScript Library
* @leafriend
* http://github.com/leafriend/stringdate.js
* MIT
*/
String.THROW_WHEN_INVALID_DATE = true
String.prototype.toDate = function(dateIsOmittable, monthIsOmittable) {
var date = null;
var str = "0000-00-00";
if (/^\d{4}-\d{2}-\d{2}$/.test(this))
str = new String(this);
else if (dateIsOmittable && /^\d{4}-\d{2}$/.test(this))
str = this + "-01";
else if (dateIsOmittable && monthIsOmittable && /^\d{4}$/.test(this))
str = this + "-01-01";
date = new Date(str);
if (isNaN(date.getTime()) || date.toISOString().substring(0, 10) != str)
if (String.THROW_WHEN_INVALID_DATE)
throw new Error("String '" + this + "' is not a form of 'yyyy-MM-dd'");
else
return undefined;
return date;
}
String.prototype.getYear = function() {
return this.toDate().getFullYear();
}
String.prototype.getMonth = function() {
return this.toDate().getMonth() + 1;
}
String.prototype.getDate = function() {
return this.toDate().getDate();
}
String.prototype.getDay = function() {
var date = this.toDate();
return date.getDay();
}
String.prototype.getLastDate = function() {
var date = this.toDate(true);
var lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
return lastDate.getDate();
}
String.prototype.isLeapYear = function() {
var date = this.toDate(true, true);
date = new Date(date.getFullYear(), 2, 0);
return date.getDate() == 29;
}
String.prototype.getDaysFrom = function(target) {
var from = this.toDate();
var to = target.toString().toDate();
return (from - to) / (1000 * 60 * 60 * 24);
}
String.prototype.addDays = function(days) {
var date = this.toDate();
date.setDate(date.getDate() + days);
return date.toISOString().substring(0, 10);
}