2 /* Utility code for dates */
4 export class DateUtil {
7 * Converts an interval string to seconds.
9 * intervalToSeconds('1 min 2 seconds')) => 62
10 * intervalToSeconds('2 days')) => 172800 (except across time changes)
11 * intervalToSeconds('02:00:23')) => 7223
13 static intervalToSeconds(interval: string): number {
15 const start = d.getTime();
16 const parts = interval.split(' ');
18 for (let i = 0; i < parts.length; i += 2) {
21 // interval is a bare hour:min:sec string
22 const times = parts[i].split(':');
23 d.setHours(d.getHours() + Number(times[0]));
24 d.setMinutes(d.getMinutes() + Number(times[1]));
25 d.setSeconds(d.getSeconds() + Number(times[2]));
29 const count = Number(parts[i]);
30 const partType = parts[i + 1].replace(/s?,?$/, '');
32 if (partType.match(/^s/)) {
33 d.setSeconds(d.getSeconds() + count);
34 } else if (partType.match(/^min/)) {
35 d.setMinutes(d.getMinutes() + count);
36 } else if (partType.match(/^h/)) {
37 d.setHours(d.getHours() + count);
38 } else if (partType.match(/^d/)) {
39 d.setDate(d.getDate() + count);
40 } else if (partType.match(/^mon/)) {
41 d.setMonth(d.getMonth() + count);
42 } else if (partType.match(/^y/)) {
43 d.setFullYear(d.getFullYear() + count);
47 return Number((d.getTime() - start) / 1000);
50 // Create a date in the local time zone with selected YMD values.
51 // Note that new Date(ymd) produces a date in UTC. This version
52 // produces a date in the local time zone.
53 static localDateFromYmd(ymd: string): Date {
54 const parts = ymd.split('-');
56 Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
59 // Note that date.toISOString() produces a UTC date, which can have
60 // a different YMD value than a date in the local time zone.
61 // This variation returns values for the local time zone.
62 // Defaults to 'now' if no date is provided.
63 static localYmdFromDate(date?: Date): string {
64 const now = date || new Date();
65 return now.getFullYear() + '-' +
66 ((now.getMonth() + 1) + '').padStart(2, '0') + '-' +
67 (now.getDate() + '').padStart(2, '0');