admin管理员组

文章数量:1414934

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

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

Share Improve this question asked Feb 19, 2021 at 23:37 FD3FD3 1,9769 gold badges37 silver badges63 bronze badges 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 – Charlie Bamford 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. – FD3 Commented Feb 19, 2021 at 23:55
Add a ment  | 

2 Answers 2

Reset to default 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 ma 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.

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

本文标签: javascriptHow to format a Date in a Specific Format in ReactjsStack Overflow