IE 火狐浏览器对时间格式的兼容性;使用原型对象的方式 prototype关键字;时间格式化

时间:2023-12-20 09:23:56

在ie中 时间格式如果用横杠来显示  “2013-05-10 19:20:59” 是可以正确识别的(如果用斜杠,IE也可以正确识别),

但是如果是火狐,则只能识别斜杠模式 “2013/05/10 19:20:59”

下面是一个类似于c#里面的拓展方法,我们给 js的日期对象 Date来增加一个格式化显示日期的方法,用到的是 prototype 关键字,通过这个关键字,我们可以给一个对象来拓展一些方法,或者是属性

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>时间兼容性问题</title>
<script type="text/javascript"> /**
* 时间对象的格式化
* 这里是通过给 Date对象的 prototype方法来加一个拓展方法来实现 format格式化的
*/
Date.prototype.format = function (format) {
/*
* format="yyyy-MM-dd hh:mm:ss";
*/
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
} if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
- RegExp.$1.length));
} for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? o[k]
: ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
} function Format(intime) {
return new Date(intime).format("yyyy-MM-dd hh:mm"); //如果这里传进来的intime是横杠时间的话,那么 new Date(intime) 返回的是个NaN
//如果是传进来的时间是斜杠的话,就能准确的显示是传进去的时间了
} var ie_time="2013-05-10 19:20:59"; //IE支持横杠时间,也支持斜杠时间 var fox_time="2013/05/10 19:20:59"; //火狐只支持斜杠时间 alert("横杠格式"+Format(ie_time));
alert("斜杠格式"+Format(fox_time));
</script>
</head>
<body>
</body></body>
</html>