Date Format(格式化日期)

js格式化日期對象,返回指定格式的日期

<script type="text/javascript">
var dateformat={
"default":"yyyy-MM-dd HH:mm:ss",
"shortdate":"yyyy-m-d",
"longdate":"yyyy-MM-dd",
"shorttime":"hh:mm:ss",
"longtime":"HH:mm:ss"
};

Date.prototype.format = function (dformat) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //12小時制
"H+": this.getHours(), //24小時制
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};

var week = {
"0": "/u65e5",
"1": "/u4e00",
"2": "/u4e8c",
"3": "/u4e09",
"4": "/u56db",
"5": "/u4e94",
"6": "/u516d"
};

if (/(y+)/.test(dformat))//
dformat = dformat.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

if (/(E+)/.test(dformat)) {
dformat = dformat.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
}
for (var k in o)
if (new RegExp("(" + k + ")").test(dformat))
dformat = dformat.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return dformat;
}
$(document).ready(function () {
$("button[name='getdate']").click(function () {
var d = new Date();
/*alert(d.format("yyyy-MM-dd"));
alert(d.format("yyyy-MM-dd hh:mm:ss"));
alert(d.format("yyyy-MM-dd h:m:ss"));*/
alert(d.format("MM/dd/yyyy h:m:ss"));
alert(d.format(dateformat.default));
alert(d.format(dateformat.longdate));
alert(d.format(dateformat.longtime));
alert(d.format(dateformat.shortdate));
alert(d.format(dateformat.shorttime));
});
});
</script>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章