Published on

How to parse Date from any format using Day.js

Authors

If you're working with external data like importing a CSV, then chances are you might have date in multiple formats and handling them manually would be a tedious task.

Thankfully, Day.js, a lightweight Javascript library handles this pretty easily.

In my case, I was importing some bank statements into my personal finance app and I noticed that the date was not normalized.

It had DD/MM/YY and also D/MM/YY (in case the day is less than 10).

Here is how to handle such cases with Day.js

Dependencies

npm i dayjs

Snippet

import dayjs from 'dayjs'

const dateFormats = ['DD/MM/YY','D/MM/YY']

const parsedDate = dayjs("20/01/22", dateFormats).toDate() // Thu Jan 20 2022 00:00:00 GMT+0530 (India Standard Time)
const anotherParsedDate = dayjs("1/01/22", dateFormats).toDate() // Sat Jan 01 2022 00:00:00 GMT+0530 (India Standard Time)

Happy parsing date!