javascript 的Date 格式化, 模仿shell中date命令的格式

shell 中显示当前的日期

[root@localhost]$ date '+%Y-%m-%d %H:%M:%S'
2015-01-19 16:24:58

把javascript 中的Date object 格式化成适合的字符串,很不方便,模拟shell中的格式

下面先用3段简单的代码来说明模拟函数中用到的特性

  1. 字符串的replace

     var a = '1234'
     undefined
     a.replace('1', 'ab') 
     "ab234"
     a
     "1234"
     b = a.replace('1', 'ab') 
     "ab234"
     b
     "ab234"
    

注意:replace是返回替换后的结果,而不是直接在字符串中更改

  1. Date的函数

     d = new Date();
     Mon Jan 19 2015 17:08:04 GMT+0800 (中国标准时间)
     d.getFullYear()
     2015
     d.getMonth()
     0
     d.getDate()
     19
     d.getHours()
     17
     d.getMinutes()
     8
     d.getSeconds()
     4
     // 单位是毫秒
     d.getTime()
     1421658484111
    

注意getTime的单位

  1. 正则匹配

     fmt = '%Y-%m-%d'
     "%Y-%m-%d"
     
     // 要特别注意其中的括号
     /(%Y)/.test(fmt)
     true
     RegExp.$1
     "%Y"
     
     /%Y/.test(fmt)
     true
     RegExp.$1
     ""
     // return替换后的结果, 而不是直接替换fmt
     fmt.replace(RegExp.$1, 'abc')
     "abc-%m-%d"
     /(Y/.test(fmt)
    
  2. 模拟的代码

     // chrome 按F12,打开drawer测试
     Date.prototype.format = function(fmt)   
     { //author: meizz   
       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), //季度   
       };   
       // 年份  2015
       if(/(%Y)/.test(fmt))   
         fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"")); 
         
       // 两位年份  15
       if(/(%y)/.test(fmt))   
         fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(2));     
       
       //getTime返回的是以毫秒为单位的,转为秒
       if(/(%s)/.test(fmt))   
         //fmt=fmt.replace(RegExp.$1, this.getTime()/1000); 
         fmt=fmt.replace(RegExp.$1, (this.getTime()+'').slice(0, 10)); 
    
       for(var k in o)   
         if(new RegExp("("+ k +")").test(fmt)){   
             fmt = fmt.replace(RegExp.$1, (o[k].length == 2 ? o[k] : '0' + o[k]));   
         }
       return fmt;   
     }     
     	
     
     > d = new Date();
     < Mon Jan 19 2015 16:54:46 GMT+0800 (中国标准时间)
    
     > d.format('%Y-%m-%d %H:%M:%S')
     < "2015-01-19 16:54:46"
    
     > d.format('%s')
     < "1421657686"
    

如果要用到正式环境,可以把上面的函数,放到一个js文件,然后在html文件中引用

原文地址:https://www.cnblogs.com/xupeiyuan/p/4246831.html