Skip to content

Commit

Permalink
date parsing: pass "strict" parameter (#250)
Browse files Browse the repository at this point in the history
Co-authored-by: Stefano Ricci <[email protected]>
  • Loading branch information
SteRiccio and SteRiccio authored Nov 15, 2024
1 parent e09b161 commit f7eabdc
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/utils/dates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,21 @@ const nowFormattedForStorage = (): string => formatForStorage(new Date())
const nowFormattedForExpression = (): string => formatForExpression(Date.now())

const parseISO = (dateStr: string): Date | undefined => (dateStr ? moment(dateStr).toDate() : undefined)
const parse = (dateStr: string, format: DateFormats, keepTimeZone = true): Date | undefined => {
const parse = (
dateStr: string,
format: DateFormats,
{ keepTimeZone = true, strict = false } = {}
): Date | undefined => {
if (!dateStr) return undefined
if (format == DateFormats.datetimeStorage) return parseISO(dateStr)
if (keepTimeZone) return moment.parseZone(dateStr, format).toDate()
return moment(dateStr, format).toDate()
if (keepTimeZone) return moment.parseZone(dateStr, format, strict).toDate()
return moment(dateStr, format, strict).toDate()
}

const isValidDateObject = (date: Date | undefined): boolean => !!date && moment(date).isValid()

const isValidDateInFormat = (dateStr: string, format: DateFormats) => {
const parsed = parse(dateStr, format)
const parsed = parse(dateStr, format, { strict: true })
return isValidDateObject(parsed)
}

Expand All @@ -55,7 +59,7 @@ const convertDate = (params: {
const { dateStr, formatFrom = DateFormats.dateStorage, formatTo, keepTimeZone = true } = params
if (Objects.isEmpty(dateStr)) return undefined

const dateParsed = parse(dateStr, formatFrom, keepTimeZone)
const dateParsed = parse(dateStr, formatFrom, { keepTimeZone })
if (!dateParsed || !moment(dateParsed).isValid()) {
return undefined
}
Expand Down

0 comments on commit f7eabdc

Please sign in to comment.