I need your help.
How can you, using javascript, convert a long date string with time to a date/time format of: mm-dd-yyyy hh:mm AM/PM
ie.
Wed May 27 10:35:00 EDT 2015
to
05-27-2015 10:35 AM
I need your help.
How can you, using javascript, convert a long date string with time to a date/time format of: mm-dd-yyyy hh:mm AM/PM
ie.
Wed May 27 10:35:00 EDT 2015
to
05-27-2015 10:35 AM
Share
Improve this question
asked May 27, 2015 at 14:55
BobbyJonesBobbyJones
1,3641 gold badge28 silver badges48 bronze badges
1
-
var d = new Date(your string here)
, then various.getXXX()
functions for the ponents: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Marc B Commented May 27, 2015 at 14:56
1 Answer
Reset to default 12Sadly, there is no flexible, built-in "format" method for JS Date
objects, so you have to do it manually (or with a plug-in/library). Here is how you would do it manually:
function formatDate(dateVal) {
var newDate = new Date(dateVal);
var sMonth = padValue(newDate.getMonth() + 1);
var sDay = padValue(newDate.getDate());
var sYear = newDate.getFullYear();
var sHour = newDate.getHours();
var sMinute = padValue(newDate.getMinutes());
var sAMPM = "AM";
var iHourCheck = parseInt(sHour);
if (iHourCheck > 12) {
sAMPM = "PM";
sHour = iHourCheck - 12;
}
else if (iHourCheck === 0) {
sHour = "12";
}
sHour = padValue(sHour);
return sMonth + "-" + sDay + "-" + sYear + " " + sHour + ":" + sMinute + " " + sAMPM;
}
function padValue(value) {
return (value < 10) ? "0" + value : value;
}
Using your example date . . .
formatDate("Wed May 27 10:35:00 EDT 2015") ===> "05-27-2015 10:35 AM"