需求
封装一个方法,将某个格式的时间字符串,转换为任意我们想要的格式。如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);