bca15963f30a59e05f1e7c6441a8660118c085c9
[evergreen-equinox.git] / Open-ILS / src / eg2 / src / app / share / util / date.ts
1
2 /* Utility code for dates */
3
4 export class DateUtil {
5
6     /**
7      * Converts an interval string to seconds.
8      *
9      * intervalToSeconds('1 min 2 seconds')) => 62
10      * intervalToSeconds('2 days')) => 172800 (except across time changes)
11      * intervalToSeconds('02:00:23')) => 7223
12      */
13     static intervalToSeconds(interval: string): number {
14         const d = new Date();
15         const start = d.getTime();
16         const parts = interval.split(' ');
17
18         for (let i = 0; i < parts.length; i += 2)  {
19
20             if (!parts[i + 1]) {
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]));
26                 continue;
27             }
28
29             const count = Number(parts[i]);
30             const partType = parts[i + 1].replace(/s?,?$/, '');
31
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);
44             }
45         }
46
47         return Number((d.getTime() - start) / 1000);
48     }
49
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('-');
55         return new Date(
56             Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
57     }
58
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');
68     }
69 }
70