fix: add date handler

This commit is contained in:
Rickard Natt och Dag 2021-04-01 11:40:38 +02:00
parent 40f7c8a59e
commit a3e0eba706
2 changed files with 52 additions and 0 deletions

View File

@ -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
lib/utils/dateHandling.ts Normal file
View File

@ -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
}