JS-Date格式化

 1 (function($){  
 2     $.formatDate = function(pattern,date){  
 3         //如果不设置,默认为当前时间  
 4         if(!date) date = new Date();  
 5         if(typeof(date) ==="string"){  
 6              if(date=="")  date = new Date();  
 7               else  date = new Date(date.replace(/-/g,"/"));  
 8         }     
 9         /*补00*/  
10         var toFixedWidth = function(value){  
11              var result = 100+value;  
12              return result.toString().substring(1);  
13         };  
14           
15         /*配置*/  
16         var options = {  
17                 regeExp:/(yyyy|M+|d+|h+|m+|s+|ee+|ws?|p)/g,  
18                 months: ['January','February','March','April','May',  
19                          'June','July', 'August','September',  
20                           'October','November','December'],  
21                 weeks: ['Sunday','Monday','Tuesday',  
22                         'Wednesday','Thursday','Friday',  
23                             'Saturday']  
24         };  
25           
26         /*时间切换*/  
27         var swithHours = function(hours){  
28             return hours<12?"AM":"PM";  
29         };  
30           
31         /*配置值*/  
32         var pattrnValue = {  
33                 "yyyy":date.getFullYear(),                      //年份  
34                 "MM":toFixedWidth(date.getMonth()+1),           //月份  
35                 "dd":toFixedWidth(date.getDate()),              //日期  
36                 "hh":toFixedWidth(date.getHours()),             //小时  
37                 "mm":toFixedWidth(date.getMinutes()),           //分钟  
38                 "ss":toFixedWidth(date.getSeconds()),           //
39                 "ee":options.months[date.getMonth()],           //月份名称  
40                 "ws":options.weeks[date.getDay()],              //星期名称  
41                 "M":date.getMonth()+1,  
42                 "d":date.getDate(),  
43                 "h":date.getHours(),  
44                 "m":date.getMinutes(),  
45                 "s":date.getSeconds(),  
46                 "p":swithHours(date.getHours())  
47         };  
48           
49         return pattern.replace(options.regeExp,function(){  
50                return  pattrnValue[arguments[0]];  
51         });  
52     };  
53       
54 })(jQuery);  
调用代码:
   
var time = new Date("2014-01-01 13:20:30");  

 console.info($.formatDate("yyyy-MM-dd hh:mm:ss ws ee","2013-1-1 13:20:30"));  

 alert($.formatDate("yyyy-MM-dd hh:mm:ss ws ee",time)); 

 

posted @ 2017-08-27 12:39  李文学  阅读(352)  评论(0)    收藏  举报