扩展 js Date 对象,实现时间美化

背景

Date对象是 javascript 中常用的对象之一,用来提供和解析时间与日期。

通常,后端返回的数据中,日期是2020-06-23T12:01:59+08:00这种,或是其他不符合前端显示需求的格式。

因此,我们需要手动将日期转换成yyyy-MM-dd hh:mm:ss的格式,这个过程,就是美化时间的过程。

如何实现时间美化

一般,我们有几种方式来对时间进行美化。

moment.js

moment.js是一个第三方包,用来操作时间和日期。

moment 提供了诸多方法,如

moment().format(‘dddd’); // 星期二
moment().format(); // 2020-06-23T12:03:59+08:00
moment().format(‘YYYY-MM-DD hh:mm:ss’); // 2020-06-23 12:09:27

这里就不多略举了,感兴趣到小伙伴可以自行去官网学习。

自己实现

我们可以在Date.prototype上封装一个方法,这样,每个日期对象实例都可以访问这个方法来美化时间。

Date.prototype.Format = function (fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if (/(y+)/i.test(fmt)){
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

		for (var k in o){
			if (new RegExp("(" + k + ")").test(fmt)) 
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));	
		}
	} 
						
	return fmt;		
};

来测试一下

new Date('2020-06-23T12:01:59+08:00').Format('yyyy-MM-dd hh:mm:ss')
// "2020-06-23 12:01:59"

new Date().Format('yyyy-MM-dd hh:mm:ss')
// "2020-06-23 12:16:15"

简单粗暴的方法

通常在一个项目中,后端返回的日期格式是保持一致的,因此,我们也可以简单粗暴的一点,直接写一个函数来美化特定格式的时间

2020-06-23T12:22:57+08:00这种为例

function timeFormat(time){
	return time.substr(0,19).replace(/T/, ' ')
}
timeFormat('2020-06-23T12:22:57+08:00')
// "2020-06-23 12:22:57"

显然,我们知道第一个参数是一个字符串,因此,可以将这个函数放进String.prototype

String.prototype.timeFormat = function(){
	return this.substr(0,19).replace(/T/, ' ')
}

'2020-06-23T12:22:57+08:00'.timeFormat()
// "2020-06-23 12:22:57"

如果大家有更好的办法,欢迎留言讨论。

猜你喜欢

转载自blog.csdn.net/zhai_865327/article/details/106920343