给Date原型附加format函数支持格式化输出

代码一:

Date.prototype.format = function(format) {
	var o = {
		"M+" : this.getMonth() + 1, //month
		"d+" : this.getDate(), //day
		"h+" : this.getHours(), //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
		"S" : this.getMilliseconds()
	//millisecond
	}
	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;
}


代码二:

Date.prototype.format = function(pattern) {
	var returnValue = pattern;
	var format = {
		"y+" : this.getFullYear(),
		"M+" : this.getMonth() + 1,
		"d+" : this.getDate(),
		"H+" : this.getHours(),
		"m+" : this.getMinutes(),
		"s+" : this.getSeconds(),
		"S" : this.getMilliseconds()
	};
	for ( var key in format) {
		var regExp = new RegExp("(" + key + ")");
		if (regExp.test(returnValue)) {
			var zero = "";
			var replacement = null;
			for ( var i = 0; i < RegExp.$1.length; i++) {
				zero += "0";
			}
			if (RegExp.$1.length == 1) {
				replacement = format[key];
			} else {
				replacement = (zero + format[key])
						.substring((("" + format[key]).length));
			}
			returnValue = returnValue.replace(RegExp.$1, replacement);
		}
	}
	return returnValue;
};


页面引入后格式化输出测试:

var dateStr = "2014-09-08";
var arr = dateStr.split("-");
var date = new Date(Number(arr[0]), Number(arr[1])-1, Number(arr[2]));
date.format("M.d");

输出结果:"9.8"

以上在IE8和Chrome测试通过。


源地址:http://www.blogjava.net/mixer-a/archive/2012/05/10/377846.html


另外说点浏览器差异:

parseInt("08");// 执行结果ie8下为0,chrome下为8
new Date("2014-08-6");// 执行结果ie8下undefined,chrome下成功创建日期Date对象

猜你喜欢

转载自blog.csdn.net/willxwan/article/details/38400855