Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format custom date using dayjs

I'm working on migrating from momentjs to dayjs

How to format a custom date format into a standard one using dayjs. For e.g., I'm trying to format a date in YYYY-MM-DD+h:mm format to YYYY-MM-DD. dayjs gives me an NaN

Works perfectly fine with moment this way -

moment(effectiveDate, 'YYYY-MM-DD+h:mm').format('YYYY-MM-DD')

There are lots of such occurrences in my codebase, so I'm trying not to rely on string manipulation to achieve this.

I've been using this repl to try things out

like image 353
SubSul Avatar asked Jul 05 '26 07:07

SubSul


1 Answers

Use dayjs version 1.8.20 and extend CustomParseFormat package.

In html file:

...
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>
<script src="https://unpkg.com/[email protected]/plugin/customParseFormat.js"></script>
...

The first let's extent dayjs object:

dayjs.extend(window.dayjs_plugin_customParseFormat);

Now, you can play with your format:

const dateString  = dayjs("2019-06-06+4:56", "YYYY-MM-DD+h:mm").format('YYYY-MM-DD');
console.log("Date: ", dateString);

Output: Date: 2019-06-06

like image 141
hoangdv Avatar answered Jul 07 '26 23:07

hoangdv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!