JavaScript时间字符串格式化

需求

封装一个方法,将某个格式的时间字符串,转换为任意我们想要的格式。如2020/5/2 17:08:46 => 2020年05月02日 17时08分46秒。

方案一:字符串拼接

思路:首先将字符串中所有代表时间的值全部获取到,再拼接成我们想要的格式。

let time = "2020/5/2 17:08:46";    // => 实际项目中是动态获取的
let arr = time.split(" ");     // => 先根据空格将日期与时间分开  ["2020/5/2","17:08:46"]
let arrLeft = arr[0].split("/");  // => ["2020","5","2"]
let arrRight = arr[1].split(":");    // => ["17","08","46"] 
time = `${arrLeft[0]}年${arrLeft[1]}月${arrLeft[2]}日 ${arrRight[0]}时${arrRight[1]}分${arrRight[2]}秒`;

这样写还有点小问题,不足位数的不能补零(如,5月应该转换为05月,而这种方式不能实现自动补零)。因此我们需要在拼接每一项之前做下面的工作:

arrLeft = arrLeft.map(function (item){
	return item.length < 2 ? "0" + item : item;   // 如果长度不足2位,则在前面补0
});
arrRight = arrRight.map(function (item){
	return item.length < 2 ? "0" + item : item;   // 时间部分同理
});

也可以先进行数组的拼接,再完成遍历补零的工作:

arr = arrLeft.concat(arrRight);    // => ["2020","5","2","17","08","46"] 
arr = arr.map(function (item){
	return item.length < 2 ? "0" + item : item;  
});

再简化,使用正则表达式:

let arr = time.split(/(?: |\/|:)/g);

or:

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

方案二:基于replace替换

let time = "2020/5/2 17:08:46";
time = time.replace("/","年").replace("/","月").replace("/","日 ").replace(":","时").replace(":","分").replace(":","秒");

然鹅,基于replace替换的方法不能实现不足十位数的补零操作,因为你也无法判断是不是需要加0。

我们可以将不足十位数补零的操作封装为一个方法:

function zero(val){
	return val.length < 2 ? "0" + val : val;
}

然后在字符串拼接的时候使用它(年份不会少于两位数):

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

方案三:正则处理

(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);
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值