2

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

2
  • 1
    The reason moment (and it's replacement luxon) exists is that Date does not do that out of the box. You can do it with string operations and the Date api Commented Feb 19, 2021 at 23:46
  • Hi @CharlesBamford thanks for the response. Makes sense. I should have posted my question earlier, I spent a while to find a solution with the date. Commented Feb 19, 2021 at 23:55

2 Answers 2

2

toLocaleString() can produce many formats, and you can choose the locale to get the format (or close to it) that you want.

The locale "en-GB" gives you almost what you want; you just need to remove the comma that it puts in...

let d = new Date(2020, 0, 22, 14, 20, 22);
let output = d.toLocaleString("en-GB")
              .replace(',' ,'');
console.log(output);

You can actually control the output further by using the options parameter.

But also see the Intl object for its DateTimeFormat constructor.

Sign up to request clarification or add additional context in comments.

Comments

2

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(" ");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.