// I can't do the normal thing here: // import { PrismaClient } from "@prisma/client"; // because something something modules. So have to do this weird thing. import pkg from '@prisma/client'; const {PrismaClient} = pkg; export const prisma = new PrismaClient(); // We use database time whenever we work with dates (eg, active pings). export async function dbDateToday() { const now: [{date: string}] = await prisma.$queryRaw`select now()::date as date`; return dbDateFromString(now[0].date); } // s is a string like "2020-01-01" assumed to be UTC. export function dbDateFromString(s: string) { const [year, month, day] = s.split('-').map(n => parseInt(n)); return new Date(Date.UTC(year, month - 1 /* ! WTF JS ! */, day)); } export function firstDayOfMonth(d: Date) { return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1)); } export function lastDayOfMonth(d: Date) { // First day of next month. const d2 = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1)); d2.setUTCDate(d2.getUTCDate() - 1); return d2; } export function monthsAgo(d: Date, n: number) { const year = d.getUTCFullYear(); const month = d.getUTCMonth(); let day = d.getUTCDate(); // Careful! A previous month might have fewer days than d has. If so, // set the day to the last day of the target month. const days = daysInMonth(new Date(Date.UTC(year, month - n, 1))); if (day > days) { day = days; } return new Date(Date.UTC(year, month - n, day)); } function daysInMonth(d: Date) { return new Date( Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0), ).getUTCDate(); }