From 973c83dc361b4f3384ef8dd34263d12941defd6d Mon Sep 17 00:00:00 2001 From: CounterFire2023 <136581895+CounterFire2023@users.noreply.github.com> Date: Thu, 11 Apr 2024 11:15:28 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0utc=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E7=9A=84=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/utcdate.util.ts | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/utils/utcdate.util.ts diff --git a/src/utils/utcdate.util.ts b/src/utils/utcdate.util.ts new file mode 100644 index 0000000..341fab2 --- /dev/null +++ b/src/utils/utcdate.util.ts @@ -0,0 +1,55 @@ +export const ONE_DAY = 24 * 60 * 60 * 1000 + +// format the date to the format we want +export const formatDate = (date: Date): string => { + const year = date.getUTCFullYear() + const month = (date.getUTCMonth() + 1 + '').padStart(2, '0') + const day = (date.getUTCDate() + '').padStart(2, '0') + return `${year}${month}${day}` +} + +// get formated datestring of yesterday +export const yesterday = (date?: Date) => { + date = date || new Date() + date.setUTCDate(date.getUTCDate() - 1) + return date +} + +export const nextday = (date?: Date) => { + date = date || new Date() + date.setUTCDate(date.getUTCDate() + 1) + return date +} + +// calc days between two Date +export function daysBetween(date1: Date, date2: Date) { + // hours*minutes*seconds*milliseconds + const diffInMs = Math.abs(date1.getTime() - date2.getTime()) + const diffInDays = Math.round(diffInMs / ONE_DAY) + return diffInDays +} + +// get begin of one day +export const getDayBegin = (date: Date): Date => { + const year = date.getUTCFullYear() + const month = date.getUTCMonth() + const day = date.getUTCDate() + return new Date(year, month, day) +} + +// get begin of n day ago +export const getNDayAgo = (n: number, begin: boolean): Date => { + const date = new Date(Date.now() - n * ONE_DAY) + if (begin) { + return getDayBegin(date) + } else { + return date + } +} + +// get begin of this month +export const getMonthBegin = (date: Date): Date => { + const year = date.getUTCFullYear() + const month = date.getUTCMonth() + return new Date(year, month, 1) +}