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
Converting a long date with time to mm-dd-yyyy hh:mm AM/PM
提问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 Date
objects, 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"