I have this simple JavaScript function below that converts a JavaScript Date into a more readable format.
Right now you have to pass in a valid Date object but I would like to modify it so that it will accept a Date object or a string with a date value and return a formatted date regardless of which version is passed into it.
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
Usage:
var d = new Date(date_string);
var e = formatDate(d);
Converts this 2015-09-16 03:18:12 into 9/16/2015 3:18 pm
I want to be able to pass in a Date object...
var dateObject = new Date(date_string);
var e = formatDate(dateObject);
or a Date string...
var dateString = `2015-09-16 03:18:12`;
var e = formatDate(dateString);