1/*!
2 * Matomo - free/libre analytics platform
3 *
4 * @link https://matomo.org
5 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
6 */
7
8export function format(date: Date): string {
9  return $.datepicker.formatDate('yy-mm-dd', date);
10}
11
12export function getToday(): Date {
13  const date = new Date(Date.now());
14
15  // undo browser timezone
16  date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
17
18  // apply Matomo site timezone (if it exists)
19  date.setHours(date.getHours() + ((window.piwik.timezoneOffset || 0) / 3600));
20
21  // get rid of hours/minutes/seconds/etc.
22  date.setHours(0);
23  date.setMinutes(0);
24  date.setSeconds(0);
25  date.setMilliseconds(0);
26  return date;
27}
28
29export function parseDate(date: string|Date): Date {
30  if (date instanceof Date) {
31    return date;
32  }
33
34  const strDate = decodeURIComponent(date).trim();
35  if (strDate === '') {
36    throw new Error('Invalid date, empty string.');
37  }
38
39  if (strDate === 'today'
40    || strDate === 'now'
41  ) {
42    return getToday();
43  }
44
45  if (strDate === 'yesterday'
46    // note: ignoring the 'same time' part since the frontend doesn't care about the time
47    || strDate === 'yesterdaySameTime'
48  ) {
49    const yesterday = getToday();
50    yesterday.setDate(yesterday.getDate() - 1);
51    return yesterday;
52  }
53
54  if (strDate.match(/last[ -]?week/i)) {
55    const lastWeek = getToday();
56    lastWeek.setDate(lastWeek.getDate() - 7);
57    return lastWeek;
58  }
59
60  if (strDate.match(/last[ -]?month/i)) {
61    const lastMonth = getToday();
62    lastMonth.setDate(1);
63    lastMonth.setMonth(lastMonth.getMonth() - 1);
64    return lastMonth;
65  }
66
67  if (strDate.match(/last[ -]?year/i)) {
68    const lastYear = getToday();
69    lastYear.setFullYear(lastYear.getFullYear() - 1);
70    return lastYear;
71  }
72
73  return $.datepicker.parseDate('yy-mm-dd', strDate);
74}
75
76export function todayIsInRange(dateRange: Date[]): boolean {
77  if (dateRange.length !== 2) {
78    return false;
79  }
80
81  if (getToday() >= dateRange[0] && getToday() <= dateRange[1]) {
82    return true;
83  }
84
85  return false;
86}
87