Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a long date with time to mm-dd-yyyy hh:mm AM/PM

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
like image 608
BobbyJones Avatar asked May 27 '15 14:05

BobbyJones


People also ask

How do I change date and time format to MM DD YYYY in Excel?

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.

How do you format a date as MM DD YYYY?

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.

How do you convert a long date to a short date?

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.

How do I convert a datetime to a specific format?

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.


1 Answers

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"
like image 154
talemyn Avatar answered Sep 19 '22 23:09

talemyn