javascript Date format(js日期格式化)

本文介绍了三种在JavaScript中实现日期格式化的实用方法。通过这些方法,开发者可以轻松地将Date对象转换为各种所需的字符串格式,如yyyy-MM-dd HH:mm:ss等。这有助于统一前端显示的时间格式,提高用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:这个很不错,好像是 csdn 的 Meizz 写的:

[javascript] view plain copy print ?
  1. // 对Date的扩展,将 Date 转化为指定格式的String  
  2. // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,  
  3. // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)  
  4. // 例子:  
  5. // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423  
  6. // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18  
  7. Date.prototype.Format = function(fmt)  
  8. { //author: meizz  
  9.   var o = {  
  10.     "M+" : this.getMonth()+1,                 //月份  
  11.     "d+" : this.getDate(),                    //日  
  12.     "h+" : this.getHours(),                   //小时  
  13.     "m+" : this.getMinutes(),                 //分  
  14.     "s+" : this.getSeconds(),                 //秒  
  15.     "q+" : Math.floor((this.getMonth()+3)/3), //季度  
  16.     "S"  : this.getMilliseconds()             //毫秒  
  17.   };  
  18.   if(/(y+)/.test(fmt))  
  19.     fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));  
  20.   for(var k in o)  
  21.     if(new RegExp("("+ k +")").test(fmt))  
  22.   fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
  23.   return fmt;  

调用方法:

[javascript] view plain copy print ?
  1. var time1 = new Date().format("yyyy-MM-dd HH:mm:ss");    
  2.  
  3. var time2 = new Date().format("yyyy-MM-dd");   

方法二:

[javascript] view plain copy print ?
  1. <mce:script language="javascript" type="text/javascript"><!-- 
  2.        
  3. /**     
  4. * 对Date的扩展,将 Date 转化为指定格式的String     
  5. * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符     
  6. * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)     
  7. * eg:     
  8. * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423     
  9. * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04     
  10. * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04     
  11. * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04     
  12. * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18     
  13. */         
  14. Date.prototype.pattern=function(fmt) {          
  15.     var o = {          
  16.     "M+" : this.getMonth()+1, //月份          
  17.     "d+" : this.getDate(), //日          
  18.     "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时          
  19.     "H+" : this.getHours(), //小时          
  20.     "m+" : this.getMinutes(), //分          
  21.     "s+" : this.getSeconds(), //秒          
  22.     "q+" : Math.floor((this.getMonth()+3)/3), //季度          
  23.     "S" : this.getMilliseconds() //毫秒          
  24.     };          
  25.     var week = {          
  26.     "0" : "/u65e5",          
  27.     "1" : "/u4e00",          
  28.     "2" : "/u4e8c",          
  29.     "3" : "/u4e09",          
  30.     "4" : "/u56db",          
  31.     "5" : "/u4e94",          
  32.     "6" : "/u516d"         
  33.     };          
  34.     if(/(y+)/.test(fmt)){          
  35.         fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));          
  36.     }          
  37.     if(/(E+)/.test(fmt)){          
  38.         fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);          
  39.     }          
  40.     for(var k in o){          
  41.         if(new RegExp("("+ k +")").test(fmt)){          
  42.             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));          
  43.         }          
  44.     }          
  45.     return fmt;          
  46. }        
  47.       
  48. var date = new Date();       
  49. window.alert(date.pattern("yyyy-MM-dd hh:mm:ss")); 
  50. // --></mce:script>     

方法三:

[javascript] view plain copy print ?
  1. Date.prototype.format = function(mask) {       
  2.       
  3.     var d = this;       
  4.       
  5.     var zeroize = function (value, length) {       
  6.       
  7.         if (!length) length = 2;       
  8.       
  9.         value = String(value);       
  10.       
  11.         for (var i = 0, zeros = ''; i < (length - value.length); i++) {       
  12.       
  13.             zeros += '0';       
  14.       
  15.         }       
  16.       
  17.         return zeros + value;       
  18.       
  19.     };         
  20.       
  21.     return mask.replace(/"[^"]*"|'[^']*'|/b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])/1?|[lLZ])/b/g, function($0) {       
  22.       
  23.         switch($0) {       
  24.       
  25.             case 'd':   return d.getDate();       
  26.       
  27.             case 'dd'return zeroize(d.getDate());       
  28.       
  29.             case 'ddd': return ['Sun','Mon','Tue','Wed','Thr','Fri','Sat'][d.getDay()];       
  30.       
  31.             case 'dddd':    return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][d.getDay()];       
  32.       
  33.             case 'M':   return d.getMonth() + 1;       
  34.       
  35.             case 'MM'return zeroize(d.getMonth() + 1);       
  36.       
  37.             case 'MMM': return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];       
  38.       
  39.             case 'MMMM':    return ['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()];       
  40.       
  41.             case 'yy'return String(d.getFullYear()).substr(2);       
  42.       
  43.             case 'yyyy':    return d.getFullYear();       
  44.       
  45.             case 'h':   return d.getHours() % 12 || 12;       
  46.       
  47.             case 'hh'return zeroize(d.getHours() % 12 || 12);       
  48.       
  49.             case 'H':   return d.getHours();       
  50.       
  51.             case 'HH'return zeroize(d.getHours());       
  52.       
  53.             case 'm':   return d.getMinutes();       
  54.       
  55.             case 'mm'return zeroize(d.getMinutes());       
  56.       
  57.             case 's':   return d.getSeconds();       
  58.       
  59.             case 'ss'return zeroize(d.getSeconds());       
  60.       
  61.             case 'l':   return zeroize(d.getMilliseconds(), 3);       
  62.       
  63.             case 'L':   var m = d.getMilliseconds();       
  64.       
  65.                     if (m > 99) m = Math.round(m / 10);       
  66.       
  67.                     return zeroize(m);       
  68.       
  69.             case 'tt'return d.getHours() < 12 ? 'am' : 'pm';       
  70.       
  71.             case 'TT'return d.getHours() < 12 ? 'AM' : 'PM';       
  72.       
  73.             case 'Z':   return d.toUTCString().match(/[A-Z]+$/);       
  74.       
  75.             // Return quoted strings with the surrounding quotes removed       
  76.       
  77.             default:    return $0.substr(1, $0.length - 2);       
  78.       
  79.         }       
  80.       
  81.     });       
  82.       
  83. };     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值