I'm getting a date string which i need to convert into other date format in the javascript.
Input Date String : 2016-03-10 16:00:00.0
Expected Output : March 10,2016
The most reliable way to format a date with the source format you're using, is to apply the following steps :
.replace(/ /g,'T')
to convert your date to ISO 8601
new Date()
.getDate()
, .getMonth()
and .getFullYear()
to get respectively the day, month and yearThe format
function below shows you the optimal way to combine those four steps :
var date = '2016-03-10 16:00:00.0';
function format(input) {
var date = new Date(input.replace(/ /g,'T'));
return [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
][date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear();
}
document.body.innerHTML = format(date); // OUTPUT : "March 10, 2016"
(See also this Fiddle).
You can also use the built-in .toLocaleDateString
method to do the formatting for you. You just need pass along the proper locale and options to match the right format, which unfortunately is only supported by modern browsers (*) :
var date = '2016-03-10 16:00:00.0';
function format(input) {
var dateFormat = { year: 'numeric', month: 'long', day: 'numeric' };
return new Date(input.replace(/ /g,'T')).toLocaleDateString('en-US', dateFormat);
}
document.body.innerHTML = format(date); // OUTPUT : "March 10, 2016"
(See also this Fiddle).
(*) According to the MDN, "Modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari nightly build