I'm getting a string date from a JSON object. I need to convert the date
"2018-05-18T04:00:00.000Z"
to. May 18 , 2018
I tried using the Date() constructor but I wasn't successful.
I've heard of Intl.DateTimeFormat
but I don't understand the documentation. Any help and explanation is appreaiated .
Now, let's see the below code example where we used the moment library for formatting dates in react. Here, we simply import the moment library and then use it within a formatDate variable. Here, in our case, the date will give output as day and then month and finally the year.
The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.
You should be able to do this purely with JavaScript, including parsing with Date() and, depending on your browser support requirements, format with toLocaleDateString().
The second example (commented out) just shows how it can work with a specific locale (as a string, though that can be an array of such strings).
function formatDate(string){
var options = { year: 'numeric', month: 'long', day: 'numeric' };
return new Date(string).toLocaleDateString([],options);
}
var dateString = "2018-05-18T04:00:00.000Z"
document.getElementById("results").innerHTML = formatDate(dateString);
// You could also provide specific locale, if needed. For example:
//function formatDate(string){
// var options = { year: 'numeric', month: 'long', day: 'numeric' };
// return new Date(string).toLocaleDateString('en-US',options);
//}
<div id="results"</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With