eletrotupi / tcc/ api/src/lib/queue/processors/insights/utils.ts5f128778e17bb00138230b7adc25bc7e69505c1f
1.1 KB | 42 lines Raw
1
import { tz } from "@date-fns/tz";
2
import { addDays, startOfDay } from "date-fns";
3

4
export function rollingPeriod(days = 7) {
5
  const periodEnd = new Date();
6
  const periodStart = new Date();
7
  periodStart.setDate(periodEnd.getDate() - days);
8

9
  return {
10
    periodStart: periodStart.toISOString(),
11
    periodEnd: periodEnd.toISOString(),
12
  };
13
}
14

15
const APP_TIMEZONE = tz("America/Sao_Paulo");
16

17
// Start of the day containing `date`, in the app's timezone
18
export function startOfAppDay(date: Date = new Date()): Date {
19
  return startOfDay(date, { in: APP_TIMEZONE });
20
}
21

22
// The app-timezone day containing `date`, as a half-open [start, end) window
23
export function appDayWindow(date: Date = new Date()): {
24
  start: Date;
25
  end: Date;
26
} {
27
  const start = startOfDay(date, { in: APP_TIMEZONE });
28
  const end = startOfDay(addDays(start, 1, { in: APP_TIMEZONE }), {
29
    in: APP_TIMEZONE,
30
  });
31

32
  return { start, end };
33
}
34

35
export function appDayPeriod(date: Date = new Date()): {
36
  periodStart: string;
37
  periodEnd: string;
38
} {
39
  const { start, end } = appDayWindow(date);
40

41
  return { periodStart: start.toISOString(), periodEnd: end.toISOString() };
42
}