javascriptmomentjsmoment-timezone

MomentJS Date format returning strange value


I have a date string as below i.e. startDate = "02-05-2024"

Now, I want this date to be formatted in the below format (to return as string to some API endpoint)

YYYY-MM-DDTHH:mm:ss.SSS[Z]

I am trying to do below

moment(startDate, 'YYYY-MM-DDTHH:mm:ss.SSS[Z]').format('YYYY-MM-DDTHH:mm:ss.SSS[Z]')

But I am seeing strange values when doing above as

2002-05-21T00:00:00.000Z

I want the output to be

2024-05-02T00:00:00.000Z

What am I doing wrong?


Solution

  • As @CBroe mentioned, the second parameter of the moment constructor is the format of the input, not the output ( which is startDate in our case ), The output format will be passed as a parameter to the format function.

    When you passed YYYY-MM-DDTHH:mm:ss.SSS[Z] as format to the input, moment misinterpreted the date like

    YYYY (year) was interpreted from the first four characters 02-0, which doesn't make sense as a year but Moment.js tries to handle it by taking 2002 (interpreting 02 as 2002 due to padding expected by YYYY).

    MM (month) was taken from the next two characters after the first dash, which is 5-. Moment.js interpreted 5 as May (05).

    DD (day) was expected after the second dash, which gave 2024 from the string "2024". So, it treated 21 as the day by splitting 2024 into 21 and 04 where 04 was ignored because the format string didn't have a place to fit it after day.

    Which results to 2002-05-21

    const startDate = "02-05-2024";
    const formattedDate = moment(startDate, "DD-MM-YYYY").format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
    
    console.log(formattedDate)
    <script src="https://cdn.jsdelivr.net/npm/moment/moment.min.js"></script>