Moment.js shows 00/Fr/2021

46 Views Asked by At

I am trying to change the format of the date using below React function below.

The date that I am passing is 2021-12-31

My function is like below

export const getDate = (date) => {
    if (date?.length > 0) {
     moment(date);
    }
    return moment(date).format('mm/dd/yyyy');
};

Two issues:

  1. Control never goes inside if, even though the length of the date is > 0.

  2. When I print return moment(date).format('mm/dd/yyyy'); it gives value as 00/Fr/2021

1

There are 1 best solutions below

12
Lars Vonk On

You are using the wrong string to format. Like explained in the comments, mm is for minutes en dd is for day in a word. You should use MM instead of mm to get the month and DD instead of dd to get the day as a number.

Here is the documentation where you can find this: https://momentjs.com/docs/#/parsing/string-format/

In the future it's good to read documentation thoroughly when you get stuck ;-)