时间字符串格式化

Posted itsmart

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了时间字符串格式化相关的知识,希望对你有一定的参考价值。

  ~function(){
          /*
          *formatTime时间格式化处理
          * @params
          *   templete:[string]我们最后期望获取日期格式的模板
          *   模板规则:{0} 年 {2-5}->月日时分秒
          * @return
          *   [string]格式化后的时间字符串
          */
          function formatTime(templete="{0}年{1}月{2}日 {3}时{4}分{5}秒"){
            //首先获取时间字符串中的年月日等信息
            let timeAry = this.match(/d+/g); //[‘2020‘,‘4‘,‘12‘,‘11‘,‘29‘,‘30‘]
            return templete.replace(/{(d+)}/g,(...[content,$1])=>{
              //content:当前本次大正则匹配的信息,$1:本次小组单独匹配的信息
              //以$1的值作为索引,到timeAry中找到对应的时间(如果没有则用‘00‘补)
              let time = timeAry[$1] || ‘00‘;
              return time.length < 2 ? time = ‘0‘+time : time;
            })
          }
          /*
          *queryURLParams:获取URL地址问号后面的参数信息(可能也包含hash值)
          * @params
          * @return
          *   [object]把所有问号参数信息以键值对的方式储存起来并且返回对象
          */
          function queryURLParams(){
            let obj = {};
            this.replace(/([^?&=#]+)=([^?&=#]+)/g,(...[,$1,$2])=> obj[$1]=$2)
            this.replace(/#([^?&=#]+)/g,(...[,$1])=>obj[‘HASH‘]=$1)
            return obj;
          }
          /*扩展到内置类Sring.prototype上*/
          [‘formatTime‘,‘queryURLParams‘].forEach(item=>{
            String.prototype[item]=eval(item);
          })
        }()
        let time = ‘2020-4-12 11:29:30‘;
        console.log(time.formatTime());//2020年04月12日 11时29分30秒
        console.log(time.formatTime(‘{0}年{1}月{2}日‘));//2020年04月12日
        time = ‘2010/4/22‘;
        console.log(time.formatTime());//2010年04月22日 00时00分00秒
        console.log(time.formatTime(‘{1}-{2}‘)); //04-22
        let url = ‘http://www.baidu.com?id=2&name=lili#value‘
        console.log(url.queryURLParams()); //{id: "2", name: "lili", HASH: "value"}
        
        

 

以上是关于时间字符串格式化的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Javadoc 中使用 @ 和 符号格式化代码片段?

为 Blogger 上的博客格式化代码片段 [关闭]

URL 片段中的多个参数

SQLite 片段函数实现不会在 TextView 中将文本格式化为 HTML

带有神秘附加字符的 Javascript Date getTime() 代码片段

java字符串格式转换成日期格式