Reputation: 1946
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
Upvotes: 2
Views: 7296
Reputation: 14800
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.
Upvotes: 2
Reputation: 1608
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(" ");
Upvotes: 2