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
In an Excel sheet, select the cells you want to format. Press Ctrl+1 to open the Format Cells dialog. On the Number tab, select Custom from the Category list and type the date format you want in the Type box. Click OK to save the changes.
First, pick the cells that contain dates, then right-click and select Format Cells. Select Custom in the Number Tab, then type 'dd-mmm-yyyy' in the Type text box, then click okay. It will format the dates you specify.
Select the dates you want to format. On the Home tab, in the Number group, click the little arrow next to the Number Format box, and select the desired format - short date, long date or time.
By using format code as 108 we can get datetime in “HH:mm: ss” format. By using format code as 109 we can get datetime in “MMM DD YYYY hh:mm:ss:fff(AM/PM)” format. By using format code as 110 we can get datetime in “MM- DD-YY” format. By using format code as 111 we can get datetime in “YYYY/MM/DD” format.
Sadly, 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With