JSON to Javascript Date & Time (HH:MM:SS AMPM) 12HR

Recently needed to convert JSON to Javascript Date & Time. Not only that I needed it in a specific format (HH:MM:SS AMPM) 12HR. The answer wasn’t so clear cut and simple, but I found what worked for me:

var dateAdded = new Date(parseInt(val.DateAdded.replace("/Date(", "").replace(")/", ""), 10));
//the below 3 were other options
//var dateAdded = new Date(+val.DateAdded.replace(/\/Date\((\d+)\)\//, '$1'));
//var dateAdded = new Date(parseInt((val.DateAdded.substr(6))));
//var dateAdded = eval(val.DateAdded.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
$(".spnDate", table).html(formatDate(dateAdded));


function formatDate(dateAdded) {
var actDate = new Date(dateAdded);
var m = actDate.getMonth();
var d = actDate.getDate();
var y = actDate.getFullYear();
var h = actDate.getHours();
var mm = actDate.getMinutes();
var s = actDate.getSeconds();
var ampm = h >= 12 ? 'PM' : 'AM';
h = h % 12;
h = h ? h : 12; // the hour '0' should be '12'
mm = ('0' + mm).slice(-2); // the minute '0' should be '00'
s = ('0' + s).slice(-2); // the second '0' should be '00'
return (m + 1) + "/" + d + "/" + y + " " + h + ":" + mm + ":" + s + " " + ampm;
}

Hope this helps someone else!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit exceeded. Please complete the captcha once again.