最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting a long date with time to mm-dd-yyyy hh:mm AMPM - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 12

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"
发布评论

评论列表(0)

  1. 暂无评论