Skip to content

Commit

Permalink
fix: add date handler
Browse files Browse the repository at this point in the history
  • Loading branch information
believer committed Apr 1, 2021
1 parent 40f7c8a commit a3e0eba
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/utils/__tests__/dateHandling.test.ts
@@ -0,0 +1,11 @@
import { parseDate } from '../dateHandling'

test.each([
['2020-12-21 09:00', '2020-12-21T08:00:00.000Z'],
['2021-05-28', '2021-05-27T22:00:00.000Z'],
['2 oktober 2020', '2020-10-01T22:00:00.000Z'],
['12 oktober 2020', '2020-10-11T22:00:00.000Z'],
['This is an invalid date', undefined],
])('handles date parsing of %s', (input, expected) => {
expect(parseDate(input)).toEqual(expected)
})
41 changes: 41 additions & 0 deletions lib/utils/dateHandling.ts
@@ -0,0 +1,41 @@
import { DateTime } from 'luxon'

const options = {
locale: 'sv',
}

export const parseDate = (input?: string): string | undefined => {
if (!input) {
return undefined
}

const dateParse = (format: string) =>
DateTime.fromFormat(input, format, options)

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

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

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

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

const dateLongForm = dateParse('dd MMMM yyyy')

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

const dateLongFormOneDigit = dateParse('d MMMM yyyy')

if (dateLongFormOneDigit.isValid) {
return dateLongFormOneDigit.toUTC().toISO()
}

// Explicit return to satisfy ESLint
return undefined
}

0 comments on commit a3e0eba

Please sign in to comment.