-
Notifications
You must be signed in to change notification settings - Fork 2
/
time.ts
38 lines (28 loc) · 1.14 KB
/
time.ts
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
// A `Time` class that stores hours and minutes. Can be used to create random
// times, convert a time to a date, or create a range of random times.
export class Time {
static random(start: Time, end: Time): Time {
const startMin = start.hour * 60 + start.minute
const endMin = end.hour * 60 + end.minute
const time = Math.floor(Math.random() * (endMin - startMin) + startMin)
return new Time(Math.floor(time / 60), time % 60)
}
static randomRange(start: Time, end: Time): [Time, Time] {
const middle = Time.random(start, end)
return [Time.random(start, middle), Time.random(middle, end)]
}
constructor(readonly hour: number, readonly minute: number) {}
toDate(baseDate: Date): Date
toDate(date: number, monthIndex: number, year: number): Date
toDate(year: number | Date, monthIndex?: number, date?: number): Date {
if (year instanceof Date) {
monthIndex = year.getMonth()
date = year.getDate()
year = year.getFullYear()
}
return new Date(year, monthIndex ?? 0, date, this.hour, this.minute)
}
toString() {
return this.hour + ":" + this.minute.toString().padStart(2, "0")
}
}