-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.js
75 lines (66 loc) · 1.29 KB
/
time.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
export default class Time {
constructor (hour, minute) {
if (hour.constructor.name == 'Time') {
this.hour = hour.hour;
this.minute = hour.minute;
} else {
this.hour = hour;
this.minute = minute;
}
}
isBefore(time) {
if (this.hour < time.hour) {
return true;
} else if (this.hour == time.hour) {
if (this.minute < time.minute) {
return true;
}
}
return false;
}
isSame(time) {
return this.hour == time.hour && this.minute == time.minute;
}
static fromString(string) {
let [hour, minute] = string.split(":");
hour = parseInt(hour);
minute = parseInt(minute || 0);
if (isNaN(hour) || isNaN(minute)) {
throw "Invalid time";
}
if (hour < 0 || hour > 23) {
throw "Invalid hour";
}
if (minute < 0 || minute > 59) {
throw "Invalid minute";
}
return new Time(hour, minute);
}
/**
*
* @param {Date} date
* @returns {Time}
*/
static fromDate(date) {
return new Time(date.getHours(), date.getMinutes());
}
toDate() {
let date = new Date();
date.setHours(this.hour);
date.setMinutes(this.minute);
return date;
}
toString() {
let minute = this.minute.toString();
if (minute.length == 1) {
minute = "0" + minute;
}
return `${this.hour}:${minute}`;
}
toJSON() {
return [
this.hour,
this.minute
]
}
}