Skip to content

Instantly share code, notes, and snippets.

@wegry
Created July 11, 2024 18:42
Show Gist options
  • Save wegry/bf38ed942d13de7d549a482761273deb to your computer and use it in GitHub Desktop.
Save wegry/bf38ed942d13de7d549a482761273deb to your computer and use it in GitHub Desktop.
Codec to parse create dayjs instances from strings
import * as t from 'io-ts'
import dayjs, { Dayjs } from 'dayjs'
import { pipe } from 'fp-ts/lib/function'
import { chain } from 'fp-ts/lib/Either'
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)
export const isoDate = new t.Type<Dayjs, string, unknown>(
'isoDate',
(u): u is Dayjs => dayjs.isDayjs(u),
(u, c) =>
pipe(
t.string.validate(u, c),
chain((d) => {
return t.success(dayjs(d, 'YYYY-MM-DD'))
})
),
(u) => u.toISOString()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment