js格式化日期格式
阿新 • • 發佈:2019-01-02
使用上述的方法即可格式化日期
<html> <head> <script language="javascript"> function Window_Load(){ var str = "Tue Jul 16 01:07:00 CST 2013"; alert(formatCSTDate(str,"yyyy-M-d")); //2013-7-16 16:24:58 alert(formatDate((new Date()),"yyyy-MM-dd")); //2013-07-15 alert(formatDate((new Date()),"yyyy/M/d")); //2013/7/15 } //格式化CST日期的字串 function formatCSTDate(strDate,format){ return formatDate(new Date(strDate),format); } //格式化日期, function formatDate(date,format){ var paddNum = function(num){ num += ""; return num.replace(/^(\d)$/,"0$1"); } //指定格式字元 var cfg = { yyyy : date.getFullYear() //年 : 4位 ,yy : date.getFullYear().toString().substring(2)//年 : 2位 ,M : date.getMonth() + 1 //月 : 如果1位的時候不補0 ,MM : paddNum(date.getMonth() + 1) //月 : 如果1位的時候補0 ,d : date.getDate() //日 : 如果1位的時候不補0 ,dd : paddNum(date.getDate())//日 : 如果1位的時候補0 ,hh : date.getHours() //時 ,mm : date.getMinutes() //分 ,ss : date.getSeconds() //秒 } format || (format = "yyyy-MM-dd hh:mm:ss"); return format.replace(/([a-z])(\1)*/ig,function(m){return cfg[m];}); } </script> </head> <body onload="Window_Load();"> </body> </html>