JavaScript日期格式化format函数的两种实现方法

作者:青柠

时间:2026-10-30

浏览:317

本文介绍JavaScript中日期格式化的两种常见实现方式。通过扩展Date原型,分别展示了基于pattern和Format方法的字符串替换逻辑,支持年月日时分秒及季度的自定义格式输出,并附带调用示例与封装建议。

文章目录

前言

前言

日期格式化方法概述

在JavaScript日常开发中,对日期进行格式化处理是一项高频需求。本文将分享两种实现时间格式化的方法,并通过具体示例进行说明。

方法一:pattern实现

第一种方法


Date.prototype.pattern=function(fmt) {  
 var o = {  
 "M+" : this.getMonth()+1, //月份  
 "d+" : this.getDate(), //日  
 "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时  
 "H+" : this.getHours(), //小时  
 "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(fmt)){  
 fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));  
 }  
 if(/(E+)/.test(fmt)){  
 fmt=fmt.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(fmt)){  
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
 }  
 }  
 return fmt;  
} 

方法一调用示例

调用方式如下:


var date = new Date(); 
window.alert(date.pattern("yyyy-MM-dd hh:mm:ss"));

方法二:Format实现

第二种方法:


// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子: 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { 
 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(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
 for (var k in o)
 if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
 return fmt;
}

方法二调用示例

调用方式如下:


 var haorooms1 = new Date().Format("yyyy-MM-dd");

 var haorooms2= new Date().Format("yyyy-MM-dd hh:mm:ss");

 alert(haorooms1 ); alert(haorooms2);

总结与封装建议

总结

上述两种方法均源自网络资源,经测试验证均可正常运行且使用便捷。建议在实际项目中将相关逻辑封装为独立函数,以便在业务代码中直接调用。这两种时间格式化方案具有较高的实用性,希望能对读者学习或工作有所帮助。如有任何疑问,欢迎留言交流。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章