-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdatetime.ts
91 lines (68 loc) · 2.44 KB
/
datetime.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import {
differenceInSeconds,
format,
getDate,
isSaturday,
isWeekend,
parse,
subMonths,
} from 'date-fns';
import { format as formatTz, toZonedTime } from 'date-fns-tz';
import { SERVER_CONFIG } from '@/config/server';
export type DateUnion = Date | string | number;
const { appTimeZone, appDateTimeFormat } = SERVER_CONFIG;
export const DATETIME = {
monthNameFormat: 'yyyy-MM',
sanFranciscoTimeZone: 'America/Los_Angeles',
} as const;
const { monthNameFormat, sanFranciscoTimeZone } = DATETIME;
/**
* Format to 'YYYY-MM'.
* @example 2024-11
*/
export const convertDateToMonthName = (date: Date): string => format(date, monthNameFormat);
/**
* Converts a 'YYYY-MM' formatted string to a Date object.
*/
export const convertMonthNameToDate = (monthString: string): Date =>
parse(monthString, monthNameFormat, new Date());
/**
* Format to 'dd/MM/yyyy HH:mm:ss' to Belgrade time zone.
* @example 05/11/2024 14:30:01
*/
export const humanFormat = (date: DateUnion): string =>
formatTz(date, appDateTimeFormat, { timeZone: appTimeZone });
export const getAppTime = (dateTime: DateUnion): Date => toZonedTime(dateTime, appTimeZone);
export const getAppNow = (): Date => getAppTime(new Date());
export const createNumberOfSecondsSincePreviousCall = (): (() => number) => {
let previousCallTime: Date | null = null;
return (): number => {
const currentTime = new Date();
if (previousCallTime === null) {
previousCallTime = currentTime;
return 0;
}
const timeDifference = differenceInSeconds(currentTime, previousCallTime);
previousCallTime = currentTime;
return timeDifference;
};
};
/**
* Is 1st or 2nd and weekend in San Francisco timezone.
* @returns true for weekend.
*/
export const isWeekendAndStartOfMonth = (dateTime: Date): boolean => {
const zonedDate = toZonedTime(dateTime, sanFranciscoTimeZone);
const dayOfMonth = getDate(zonedDate);
const isFirstOrSecond = dayOfMonth === 1 || dayOfMonth === 2;
const isWeekendDay = isWeekend(zonedDate);
// is weekend but Friday was 1st
const isSecondAndSaturday = dayOfMonth === 2 && isSaturday(zonedDate);
const result = isFirstOrSecond && isWeekendDay && !isSecondAndSaturday;
return result;
};
export const createOldMonthName = (monthName: string, monthsAgo: number): string => {
const date = parse(monthName, monthNameFormat, new Date());
const previousDate = subMonths(date, monthsAgo);
return format(previousDate, monthNameFormat);
};