Skip to content

Commit

Permalink
fix: handle iso date strings
Browse files Browse the repository at this point in the history
  • Loading branch information
believer committed Apr 1, 2021
1 parent 3ba96fe commit ca0a3e4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
2 changes: 2 additions & 0 deletions lib/utils/__tests__/dateHandling.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ test.each([
['12 oktober 2020', '2020-10-11T22:00:00.000Z'],
['5 oktober 2020 11:34', '2020-10-05T09:34:00.000Z'],
['15 oktober 2020 11:34', '2020-10-15T09:34:00.000Z'],
['2020-12-18T15:59:46.34', '2020-12-18T14:59:46.340Z'],
['2020-12-18T15:59:46.340Z', '2020-12-18T15:59:46.340Z'],
['This is an invalid date', undefined],
])('handles date parsing of %s', (input, expected) => {
expect(parseDate(input)).toEqual(expected)
Expand Down
16 changes: 12 additions & 4 deletions lib/utils/dateHandling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const options = {
locale: 'sv',
}

const toISOString = (date: DateTime) => date.toUTC().toISO()

export const parseDate = (input?: string): string | undefined => {
if (!input) {
return undefined
Expand All @@ -12,28 +14,34 @@ export const parseDate = (input?: string): string | undefined => {
const dateParse = (format: string) =>
DateTime.fromFormat(input, format, options)

const dateISO = DateTime.fromISO(input)

if (dateISO.isValid) {
return toISOString(dateISO)
}

const dateAndTime = dateParse('yyyy-MM-dd HH:mm')

if (dateAndTime.isValid) {
return dateAndTime.toUTC().toISO()
return toISOString(dateAndTime)
}

const onlyDate = dateParse('yyyy-MM-dd')

if (onlyDate.isValid) {
return onlyDate.toUTC().toISO()
return toISOString(onlyDate)
}

const dateLongForm = dateParse('d MMMM yyyy')

if (dateLongForm.isValid) {
return dateLongForm.toUTC().toISO()
return toISOString(dateLongForm)
}

const dateTimeLongForm = dateParse('d MMMM yyyy HH:mm')

if (dateTimeLongForm.isValid) {
return dateTimeLongForm.toUTC().toISO()
return toISOString(dateTimeLongForm)
}

// Explicit return to satisfy ESLint
Expand Down

0 comments on commit ca0a3e4

Please sign in to comment.