我需要你的帮助,
我有前两种日期格式使用服务器返回的长日期。但是,当我将函数dateToMDY(date)调用到第3个div时,日期格式仍为dd / mm / yyyy。太痛苦了。我在这做错了什么?一切看起来都井然有序。我错过了什么吗?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript">
function test() {
var x = "Mon Mar 5 00:00:00 EST 2012"
var y = "05/03/2012"
document.getElementById('divy1').innerHTML = dateToDMY(new Date(x))
document.getElementById('divy2').innerHTML = dateToMDY(new Date(x))
document.getElementById('divy3').innerHTML = dateToMDY(new Date(y))
}
function dateToDMY(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return ''+ (d <= 9 ? '0' + d : d) +'/'+ (m<=9 ? '0' + m : m) + '/' + y;
}
function dateToMDY(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return ''+ (m<=9 ? '0' + m : m)+'/'+ (d <= 9 ? '0' + d : d) + '/' + y;
}
</script>
</head>
<body onload="test()">
dd/mm/yyyy (DatePicker)
<div id="divy1"></div>
<br>
mm/dd/yyyy (SQL)
<div id="divy2"></div>
<br>
Default Date String should be converted to mm/dd/yyyy
<div id="divy3"></div>
</body>
</html>
答案 0 :(得分:0)
Date.prototype.formatDate = function (format) {
var date = this,
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds();
if (!format) {
format = "MM/dd/yyyy";
}
format = format.replace("MM", month.toString().replace(/^(\d)$/, '0$1'));
if (format.indexOf("yyyy") > -1) {
format = format.replace("yyyy", year.toString());
} else if (format.indexOf("yy") > -1) {
format = format.replace("yy", year.toString().substr(2, 2));
}
format = format.replace("dd", day.toString().replace(/^(\d)$/, '0$1'));
if (format.indexOf("t") > -1) {
if (hours > 11) {
format = format.replace("t", "pm");
} else {
format = format.replace("t", "am");
}
}
if (format.indexOf("HH") > -1) {
format = format.replace("HH", hours.toString().replace(/^(\d)$/, '0$1'));
}
if (format.indexOf("hh") > -1) {
if (hours > 12) {
hours -= 12;
}
if (hours === 0) {
hours = 12;
}
format = format.replace("hh", hours.toString().replace(/^(\d)$/, '0$1'));
}
if (format.indexOf("mm") > -1) {
format = format.replace("mm", minutes.toString().replace(/^(\d)$/, '0$1'));
}
if (format.indexOf("ss") > -1) {
format = format.replace("ss", seconds.toString().replace(/^(\d)$/, '0$1'));
}
return format;
};
var d1 = new Date(1351596249000);
console.log(d1.formatDate("dd/MM/yy hh:mm"));
var d2 = new Date();
console.log(d2.formatDate("dd/MM/yy HH:mm t"));
答案 1 :(得分:0)
此处的问题是new Date()
。它不知道提供的日期,'05 / 03/2012',是3月5日。它假定它是5月3日。这是another way。
答案 2 :(得分:0)