Converting string date in react/javascript
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>
You can use Moment.js to do this.
const date = moment("2018-05-18T04:00:00.000Z").format('DD MMM, YYYY');
console.log(date);
// May 18, 2018
Here's a fiddle.
You've created a new Date object correctly and JavaScript stored the correct date. The issue has to do with Locale. In this next line of code, JS has created and stored that exact time. But when we ask for an output from JS we usually get exactly what we ask. From you're example, you've asked for the date based upon a locale that is most likely in the USA. So this:
new Date('2018-05-18T04:00:00Z').toLocaleString(); //(or .toString()
will give you exactly the result you ask, which is a UTC time shifted to a different locale (I've left the time on for demonstration).
On the other hand, using this:
new Date('2018-05-18T04:00:00Z').toUTCString();
Will produce the result you expect because it enforces the correct locale to be UTC.
document.querySelector('#a').innerText = new Date('2018-05-18T04:00:00Z').toString();
document.querySelector('#b').innerText = new Date('2018-05-18T04:00:00Z').toUTCString();
Incorrect: <p id="a"></p>
<hr>
Correct: <p id="b"></p>