3

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

SubSul
  • 2,523
  • 1
  • 17
  • 27

2 Answers2

4

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

hoangdv
  • 15,138
  • 4
  • 27
  • 48
0

You can do this way, hope this will help you

let customFormat = dayjs('2019-06-06+4:56'.replace('+','T')+':00').format('YYYY-MM-DD')
console.log('Custom format conversion1 - ', customFormat )
Narendra Chouhan
  • 2,291
  • 1
  • 15
  • 24
  • Thanks, I was able to figure this out, but I'm trying to figure out a way without any string manipulations. I have quite a few different date formats and wouldnt want to rely on string manipulations everywhere. If nothing works out, this would have to be my last resort though. – SubSul Feb 26 '20 at 04:24
  • yes sure, but i don't think so that there is any option rather then using string manipulations, i have cross check with the document dayjs :- http://zetcode.com/javascript/dayjs/ – Narendra Chouhan Feb 26 '20 at 04:28