J19 时间字符串格式化

123 阅读2分钟

把一个时间日期字符串转化为我们想要的格式

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

//2020年03月11日 14时10分00秒
let time="2020/3/11 14:10:00";

//1.把原始字符串代表时间的值获取到,最后拼接成我们想要的
let arr=time.split(" ");
// console.log(arr);//=>["2020/3/11", "14:00:00"]

let arrLeft=arr[0].split("/");
//  console.log(arrLeft);//=>["2020", "3", "11"]

 let arrRight=arr[1].split(":");
//  console.log(arrRight);//=>["14", "00", "00"]

arr=arrLeft.concat(arrRight);
// console.log(arr);//=>["2020", "3", "11" ,"14", "00", "00"]
arr=arr.map(function(item){
	return item.length<2?"0"+item:item;
});

time=`${arr[0]}${arr[1]}${arr[2]} ${arr[3]}${arr[4]}${arr[5]}秒`;
console.log(time);//=>2020年3月11 14时00分00秒

2.match方法实现

let time = '2020/3/11 14:10:0';
let arr = time.match(/\d+/g); //=>["2020", "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); //=>2020年03月11日 14时10分00秒

3.正则表达式

let time = '2020/3/11 14:10:0';
let arr = time.split(/(?: |\/|:)/g); //=>["2020", "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); //=>2020年03月11日 14时10分00秒 

4.正则封装一个方法

(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 = '2020-3-11 14:10:0';
console.log(time.formatTime());//=>2020年03月11日 14时10分00秒
console.log(time.formatTime('{1}-{2} {3}:{4}'));//=>03-11 14:10
console.log(time.formatTime('{0}年{1}月{2}日'));//=>2020年03月11日