javascript 将带时间的长日期转换为 mm-dd-yyyy hh:mm AM/PM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30486086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:14:52  来源:igfitidea点击:

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

javascriptdatedatetime

提问by BobbyJones

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

您如何使用 javascript 将带有时间的长日期字符串转换为日期/时间格式:mm-dd-yyyy hh:mm AM/PM

ie.

IE。

Wed May 27 10:35:00 EDT 2015

to

05-27-2015 10:35 AM

回答by talemyn

Sadly, there is no flexible, built-in "format" method for JS Dateobjects, so you have to do it manually (or with a plug-in/library). Here is how you would do it manually:

遗憾的是,JSDate对象没有灵活的内置“格式化”方法,因此您必须手动(或使用插件/库)来完成。以下是您手动执行的方法:

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 . . .

使用您的示例 date 。. .

formatDate("Wed May 27 10:35:00 EDT 2015")  ===>  "05-27-2015 10:35 AM"