48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
import { format, addHours } from "date-fns";
|
|
import { TZDate } from "@date-fns/tz";
|
|
import { UTCDate, utc } from "@date-fns/utc";
|
|
import spacetime from "spacetime";
|
|
|
|
export function dateFromInput(input: { dateQuery: string, timezone: string }) {
|
|
let t: string;
|
|
try {
|
|
t = format(new UTCDate(input.dateQuery), "yyyy-MM-dd", { in: utc });
|
|
}
|
|
catch (e) {
|
|
const now_here = spacetime.now(input.timezone);
|
|
switch (input.dateQuery) {
|
|
case "today":
|
|
t = now_here.format("yyyy-MM-dd");
|
|
break;
|
|
case "yesterday":
|
|
t = now_here.subtract(1, "day").format("yyyy-MM-dd");
|
|
break;
|
|
case "tomorrow":
|
|
t = now_here.add(1, "day").format("yyyy-MM-dd");
|
|
break;
|
|
default:
|
|
throw new Error("Invalid dateQuery");
|
|
}
|
|
}
|
|
// console.log(`dateFromInput(${input.dateQuery}, ${input.timezone}) = ${t}`);
|
|
return t;
|
|
}
|
|
|
|
function generateHour(d, t) {
|
|
const dt: TZDate = addHours(d, t);
|
|
console.log(dt);
|
|
return {
|
|
date: format(dt, 'yyyy-MM-dd'),
|
|
time: parseInt(format(dt, 'H')),
|
|
};
|
|
}
|
|
|
|
export function hoursListInUTC(input: { dateQuery: string, timezone: string }) {
|
|
const midnight = spacetime(input.dateQuery, input.timezone).time('00:00');
|
|
const hours = Array.from({ length: 24 }, function (_, i) {
|
|
const utcMoment = midnight.add(i, 'hour').goto('UTC');
|
|
return { date: utcMoment.format('hh'), time: utcMoment.hour() };
|
|
});
|
|
return hours;
|
|
}
|