在Java,net中时间类都有相应自定义时间格式,可以很方便的DateTime().ToString("yyyyMMdd HH:mm:ss"),实现自己想要的时间格式。但脚本时间类没有这个函数,可以随意定义事件格式,所在前一段时间里做项目自己扩展时间格式化函数,现在拿出与大家分享。代码如下:
/*时间格式化 http://www.naoqiu.com*/
Date.prototype.format = function (format) {
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;
}
下面再补充两个自定函数,一个是判断是否为时间变量,另一个是字符串转化时间变量。代码如下:
/*检测是否为时间 http://power.76741.com*/
function isDate(date) {
date = date == undefined ? "" : date.toString().toDate();
return new Date(date) != "Invalid Date" && new Date(date) != "NaN";
}
/*时间格式化*/
String.prototype.toDate = function () {
return new Date(this.replace(RegExp("-", "g"), "/"));
}