Mirror of https://github.com/roostorg/coop
github.com/roostorg/coop
1import { type Opaque } from 'type-fest';
2
3import { instantiateOpaqueType } from './typescript-types.js';
4
5export const SECOND_MS = 1000;
6export const MINUTE_MS = SECOND_MS * 60;
7export const HOUR_MS = MINUTE_MS * 60;
8export const DAY_MS = HOUR_MS * 24;
9export const WEEK_MS = DAY_MS * 7;
10export const MONTH_MS = DAY_MS * 30;
11export const YEAR_MS = DAY_MS * 365;
12
13// NB: we call this DateOnlyString to avoid a conflict with the DateString type
14// in @roostorg/types.
15export type DateOnlyString = Opaque<string, 'DateOnlyString'>;
16
17/**
18 * Returns a YYYY-MM-DD string for the given Date instance. The date shown in
19 * the string represents the date _in UTC time_ of the passed in Date object.
20 */
21export function getUtcDateOnlyString(date = new Date()) {
22 return instantiateOpaqueType<DateOnlyString>(
23 date.toISOString().split('T')[0],
24 );
25}
26
27export function dateWithoutSeconds(date: Date) {
28 const res = new Date(date);
29 res.setSeconds(0, 0);
30 return res;
31}
32
33export function getUtcParts(date: Date) {
34 return {
35 year: date.getUTCFullYear(),
36 month: date.getUTCMonth() + 1,
37 date: date.getUTCDate(),
38 hour: date.getUTCHours(),
39 minute: date.getUTCMinutes(),
40 second: date.getUTCSeconds(),
41 milliseconds: date.getUTCMilliseconds(),
42 };
43}
44
45export function isValidDate(date: Date) {
46 return !isNaN(date.getTime());
47}
48
49export function getStartOfDayInTimezone(timezone: string) {
50 const dateInTimezone = new Date(
51 new Date().toLocaleString('en-US', { timeZone: timezone }),
52 );
53 dateInTimezone.setHours(0, 0, 0, 0);
54 return dateInTimezone;
55}
56
57export function getEndOfDayInTimezone(timezone: string) {
58 const dateInTimezone = new Date(
59 new Date().toLocaleString('en-US', { timeZone: timezone }),
60 );
61 dateInTimezone.setHours(23, 59, 59, 999);
62 return dateInTimezone;
63}