javascript 时间格式化
在前端应用开发中,难免会遇到进行时间格式化,一般遇到最多的情况就是时间戳,有了时间戳就可以转换为我们能看明白的时间;那么,为什么不封装一个方法供自己使用呢?
/**
* 在Date原型上绑定Format方法
* 年(Y)可以用 1-4 个占位符,
* 月(M)、日(D)、小时(h)、分(m)、秒(s) 可以用 1-2 个占位符,
* 毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
*/
Date.prototype.Format = function(style) {
var formatTime = '';
var timeObj = {
"M+": this.getMonth() + 1, //月份
"D+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"S": this.getMilliseconds() //毫秒
};
if (/(Y+)/.test(style)){
formatTime = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in timeObj ){
if (new RegExp("(" + k + ")").test(formatTime)){
formatTime = formatTime.replace(RegExp.$1, (RegExp.$1.length == 1) ? (timeObj[k]) : (("00" + timeObj[k]).substr(("" + timeObj[k]).length)) );
}
}
return formatTime ;
}
console.log((new Date()).Format("YYY-MM-DD hh:mm:ss")); //使用时,直接调用
注意:一定要注意输入的格式字母大小写!
相互学习,仅供参考