js处理时间字符串的三种方式

 2023-12-21  阅读 2  评论 0

摘要:svn能否搭建在云服务器上 SVN管理的数据存放在中央资料档案库(Repository)中。该档案库会记录文件的每一次变动,这样您就可以把数据恢复至旧版本或浏览文件的变动历史。 一、正则处理(优) (proto => {     function formatTime(t

js处理时间字符串的三种方式

svn能否搭建在云服务器上

SVN管理的数据存放在中央资料档案库(Repository)中。该档案库会记录文件的每一次变动,这样您就可以把数据恢复至旧版本或浏览文件的变动历史。

一、正则处理(优)

(proto => {

    function formatTime(template = ‘{0}年{1}月{2}日 {3}时{4}分{5}秒’) {

        let arr = this.match(//d+/g);

        return template.replace(//{(/d+)/}/g, (_, n) => {

            let item = arr[n] || ‘0’;

            item.length < 2 ? item = ‘0’ + item : null;

            return item;

        });

    }

    proto.formatTime = formatTime;

})(String.prototype);

 

let time = ‘-3-11 14:10:0’;

console.log(time.formatTime());//=>年03月11日 14时10分00秒

console.log(time.formatTime(‘{1}-{2} {3}:{4}’));//=>03-11 14:10

console.log(time.formatTime(‘{0}年{1}月{2}日’));//=>年03月11日

优点:灵活,万能(封装一个公共的,万能的时间格式化的方法)

二、字符串截取方式(良)

let time = ‘/3/11 14:10:0’;

 

/* 1.把原始字符串中代表时间的值都获取到,最后拼接成为我们想要的即可 */

let arr = time.split(‘ ‘); //=>[“/3/11”, “14:10:0”]

let arrLeft = arr[0].split(‘/’); //=>[“”, “3”, “11”]

let arrRight = arr[1].split(‘:’); //=>[“14”, “10”, “0”]

arr = arrLeft.concat(arrRight); //=>[“”, “3”, “11”, “14”, “10”, “0”]

 

// 在拼接之前,需要把ARRLEFT和ARRRIGHT中不足两位的数字,前面补充零

arr = arr.map(item => item.length < 2 ? ‘0’ + item : item);

time = `${arr[0]}年${arr[1]}月${arr[2]}日 ${arr[3]}时${arr[4]}分${arr[5]}秒`;

 

console.log(time);//=>”年03月11日 14时10分00秒”

优缺点:思路简单,但不够灵活

字符串截取结合简单正则处理(1)

let time = ‘/3/11 14:10:0’;

 

let arr = time.match(//d+/g); //=>[“”, “3”, “11”, “14”, “10”, “0”]

arr = arr.map(item => item.length < 2 ? ‘0’ + item : item);

time = `${arr[0]}年${arr[1]}月${arr[2]}日 ${arr[3]}时${arr[4]}分${arr[5]}秒`;

 

console.log(time);//=>年03月11日 14时10分00秒

不够灵活

字符串截取结合简单正则处理(2)

let time = ‘/3/11 14:10:0’;

 

// 不足十位补充零的操作封装为一个方法

function zero(val) {

    return val.length < 2 ? ‘0’ + val : val;

}

 

let arr = time.split(/(?: |//|:)/g); //=>[“”, “3”, “11”, “14”, “10”, “0”]

time = `${arr[0]}年${zero(arr[1])}月${zero(arr[2])}日 ${zero(arr[3])}时${zero(arr[4])}分${zero(arr[5])}秒`;

 

console.log(time);//=>年03月11日 14时10分00秒

不够灵活

三、replace替换(差)

let time = ‘/3/11 14:10:0’;

 

time = time.replace(‘/’, ‘年’).replace(‘/’, ‘月’).replace(‘ ‘, ‘日 ‘).replace(‘:’, ‘时’).replace(‘:’, ‘分’) + ‘秒’;

 

console.log(time); //=>年3月11日 14时10分0秒

缺点:没有实现不足十位数字的补充零

版权声明:xxxxxxxxx;

原文链接:https://lecms.nxtedu.cn/yunzhuji/80152.html

发表评论:

验证码

管理员

  • 内容1196553
  • 积分0
  • 金币0
关于我们
lecms主程序为免费提供使用,使用者不得将本系统应用于任何形式的非法用途,由此产生的一切法律风险,需由使用者自行承担,与本站和开发者无关。一旦使用lecms,表示您即承认您已阅读、理解并同意受此条款的约束,并遵守所有相应法律和法规。
联系方式
电话:
地址:广东省中山市
Email:admin@qq.com
注册登录
注册帐号
登录帐号

Copyright © 2022 LECMS Inc. 保留所有权利。 Powered by LECMS 3.0.3

页面耗时0.0119秒, 内存占用359.73 KB, 访问数据库18次