Search code examples
javascriptdayjs

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


Solution

  • Use dayjs version 1.8.20 and extend CustomParseFormat package.

    In html file:

    ...
    <script src="https://unpkg.com/dayjs@1.8.20/dayjs.min.js"></script>
    <script src="https://unpkg.com/dayjs@1.8.20/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