How to format a Date in a Specific Format in React.js?

I want to show the full date formatted from this 2020-11-09T17:50:00.000Z
to this
22/1/2020 14:20:22 format.
I know how get the desired format via moment.js, but want to achieve this with JavaScript Date.
Here is what I have now, but this is not what I want.

let d = new Date("2020-11-09T17:50:00.000Z".toLocaleString("en-US"))
        console.log(d);

Any help will be appreciated

46 thoughts on “How to format a Date in a Specific Format in React.js?”

  1. You can always do it manually, the Date API only has a limited set of functions like .toLocaleDateString() which will give you "11/9/2020" and .toGMTString() will return "Mon, 09 Nov 2020 17:50:00 GMT".

    Using your Date APIs, you can build the string yourself using what you have.

    var timeString = d.toGMTString().split(" ")[4]; //This will return your 17:50:00
    //For the date string part of it
    var dateNumber = d.getDate();
    var monthNumber = d.getMonth() + 1;
    var yearNumber = d.getFullYear();
    var dateString = `${dateNumber}/${monthNumber}/${yearNumber}`;
    var finalDateString = [dateString, timeString].join(" ");
    
    Reply

Leave a Comment