This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalDate.js
65 lines (53 loc) · 2.04 KB
/
LocalDate.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
// @flow
import { pad2 } from './util';
function warn(message: string) {
if (process.env.NODE_ENV !== 'production') {
console.warn(message); // eslint-disable-line no-console
}
}
export default class LocalDate extends Date {
static ISO_DATE_FORMAT = /^(\d{4})-(\d{2})-(\d{2})$/
static test(isoDate: string) {
return LocalDate.ISO_DATE_FORMAT.test(isoDate);
}
constructor(value: LocalDate | string | void) {
if (typeof value === 'undefined') {
const now = new Date();
super(now.getFullYear(), now.getMonth(), now.getDate());
} else if (value instanceof LocalDate) {
super(value.getFullYear(), value.getMonth(), value.getDate());
} else if (typeof value === 'string' && LocalDate.ISO_DATE_FORMAT.test(value)) {
const [
year,
month,
date
] = LocalDate.ISO_DATE_FORMAT.exec(value).slice(1).map(s => parseInt(s, 10));
super(year, month - 1, date, 0, 0, 0, 0);
} else {
if (process.env.NODE_ENV !== 'production') {
throw new Error('Invalid date supplied. Please specify an ISO date string (YYYY-MM-DD) or a LocalDate object.\nhttps://github.com/buildo/local-date#parser'); // eslint-disable-line max-len
} else {
throw new Error('Invalid date supplied');
}
}
}
toISOString(): string {
return [this.getFullYear(), pad2(this.getMonth() + 1), pad2(this.getDate())].join('-');
}
getHours(): number {
warn('You shouldn\'t use LocalDate.getHours as LocalDate is time agnostic.');
return Date.prototype.getHours.call(this);
}
getMinutes(): number {
warn('You shouldn\'t use LocalDate.getMinutes as LocalDate is time agnostic.');
return Date.prototype.getMinutes.call(this);
}
getSeconds(): number {
warn('You shouldn\'t use LocalDate.getSeconds as LocalDate is time agnostic.');
return Date.prototype.getSeconds.call(this);
}
getMilliseconds(): number {
warn('You shouldn\'t use LocalDate.getMilliseconds as LocalDate is time agnostic.');
return Date.prototype.getMilliseconds.call(this);
}
}