Matt Matt -4 years ago 113
Javascript Question

Formatting JSON date in Javascript rendered HTML

Having trouble formatting a date from JSON from

2017-03-22 00:00:00 -0400
format to
MMM/DD/YYYY
format.

var formatResults = function(data) {
return "<tr>" +
"<td data-title=\"amount\" class=\"amount\">" + data['amount'] + "<span class=\"result\">result</span></td>" +
"<td data-title=\"case\">" + data['case'] + "</td>" +
"<td data-title=\"title\">Title of Case</td>" +
"<td data-title=\"user\" class=\"numeric\">" + data['person'] + "</td>" +
"<td data-title=\"location\" class=\"numeric\">" + data['office'] + "</td>" +
"<td data-title=\"date\" class=\"numeric\">" + data['date'] +
"</td>" +
"</tr>";
};


How can I transform the date passed directly from the JSON into the necessary format above?

Answer Source

You can use new Date(dateString) as long as the format can be parsed by Date.parse()

var date = new Date('2017-03-22 00:00:00 -0400');
var formattedDate = date.getMonth()+'/'+date.getDate()+'/'+date.getFullYear();

console.log(formattedDate);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download