0

In a React project, I'am getting date output in the form of xxth Mar XXXX format and I need it in DD/MM/YY.

Take an example: 18th Mar 2021 is what I'am getting, expected output should be like 18/03/2021

What is the best solution?

Rakesh kumar Oad
  • 1,332
  • 1
  • 15
  • 24
Pranav
  • 1,487
  • 2
  • 25
  • 53
  • 2
    Does this answer your question? [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) –  Mar 18 '21 at 07:20
  • 1
    [Here](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) you will find anything you want. Or you can use `moment` library like: `moment(date).format("DD/MM/YYYY")` –  Mar 18 '21 at 07:20

2 Answers2

0

You can use Moments.js Library , then you can use moment(date).format("DD/MM/YYYY") to get the desire output.

0

I have tried moment library, but it doesn't work as expected.

const moment = require('moment');

console.log(moment('12th Mar 2021').format('DD/MM/YYYY'));

I got the following warning message, and the date fell back to Date():

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

So I have switched to dayjs, and it works

const customParseFormat = require('dayjs/plugin/customParseFormat');
// without customParseFormat, it won't work
const dayjs = require('dayjs');
dayjs.extend(customParseFormat);

console.log(dayjs('12th Mar 2021', 'DD[th] MMM YY').format('DD/MM/YYYY'));

Furthermore, dayjs is much more smaller than moment.

Ngo Quang Duong
  • 131
  • 1
  • 2
  • 7