Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string date in react/javascript

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 .

like image 537
bruce Avatar asked May 20 '18 01:05

bruce


People also ask

How do I change the date format in react JS?

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.

How do you parse a date?

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.


Video Answer


1 Answers

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>
like image 57
ninjaAF Avatar answered Sep 19 '22 16:09

ninjaAF