56 lines
1.3 KiB
TypeScript
56 lines
1.3 KiB
TypeScript
import { dt } from "@/lib/dt"
|
|
|
|
import type { Dayjs } from "dayjs"
|
|
|
|
/**
|
|
* Get valid dates from stringFromDate and stringToDate making sure that they are not in the past and chronologically correct
|
|
* @example const { fromDate, toDate} = getValidDates("2021-01-01", "2021-01-02")
|
|
*/
|
|
export function getValidDates(
|
|
stringFromDate: string | undefined,
|
|
stringToDate: string | undefined
|
|
): { fromDate: Dayjs; toDate: Dayjs } {
|
|
const fromDate = getValidFromDate(stringFromDate)
|
|
const toDate = getValidToDate(stringToDate, fromDate)
|
|
|
|
return { fromDate, toDate }
|
|
}
|
|
|
|
/**
|
|
* Get valid fromDate from stringFromDate making sure that it is not in the past
|
|
*/
|
|
export function getValidFromDate(stringFromDate: string | undefined): Dayjs {
|
|
const now = dt().utc()
|
|
if (!stringFromDate) {
|
|
return now
|
|
}
|
|
const toDate = dt(stringFromDate)
|
|
|
|
const yesterday = now.subtract(1, "day")
|
|
if (!toDate.isAfter(yesterday)) {
|
|
return now
|
|
}
|
|
|
|
return toDate
|
|
}
|
|
|
|
/**
|
|
* Get valid toDate from stringToDate making sure that it is after fromDate
|
|
*/
|
|
export function getValidToDate(
|
|
stringToDate: string | undefined,
|
|
fromDate: Dayjs | Date
|
|
): Dayjs {
|
|
const tomorrow = dt().utc().add(1, "day")
|
|
if (!stringToDate) {
|
|
return tomorrow
|
|
}
|
|
|
|
const toDate = dt(stringToDate)
|
|
if (toDate.isAfter(fromDate)) {
|
|
return toDate
|
|
}
|
|
|
|
return tomorrow
|
|
}
|