-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (40 loc) · 1.33 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
'use strict';
// YYYY-MM-DD
var DATE_FORMAT = /^(\d+)-(\d{2})-(\d{2})$/;
function JustDate(value) {
if (!value) {
this.date = null;
}
else if (value instanceof Date) {
this.date = new Date(value.getFullYear(), value.getMonth(), value.getDate());
}
else if (typeof value === 'string' && DATE_FORMAT.test(value)) {
var dateParts = value.match(DATE_FORMAT).splice(1);
this.date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
}
else {
throw new Error('Invalid date supplied. Please specify a date object or date string in YYYY-MM-DD format.');
}
return this;
}
JustDate.prototype.toString = function () {
if (!this.date) {
return '';
}
var date = this.date;
// Why not `date.toISOString()`? We want the date in local time, which should have a time of zero. If
// We convert to an ISO string, the timezone will convert to UTC, which may shift the date.
var dateString = [date.getFullYear(), pad2(date.getMonth() + 1), pad2(date.getDate())].join('-');
return dateString;
};
JustDate.prototype.toFormattedString = function () {
if (!this.date) {
return '';
}
var date = this.date;
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
};
function pad2(number) {
return number < 10 && number >= 0 ? '0' + number : number;
}
module.exports = JustDate;