Published on

Parsing Date with suffix like st, nd, rd, th with Day.js

Authors

Here is how to convert date with ordinal suffix (like "st", "nd", "rd", or "th") format by using day.js

Install the dependency if it's not already done.

npm install dayjs

Let's assume that I've a case in which I want to convert 3rd Jun, 2022 01:30 AM into a proper date using Day.js

Here's how to do it:

import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat.js";
dayjs.extend(customParseFormat);

const dateString = '3rd Jun, 2022 01:30 AM';
// "Do" represents day of the month with ordinal suffix
const dateFormat = 'Do MMM, YYYY hh: mm A';

const parsedDate = dayjs(dateString, dateFormat);

const jsDate = parsedDate.toDate() // Fri Jun 03 2022 01:00:00 GMT+0530 (India Standard Time)

Happy formatting date!