最近写前端页面总是会遇到与时间显示相关的需求
比如:
2022-12-02 22:00:00
2022.12.02 22:00:00
2022-12-02
2022.12.02
22:00:00
一般来说这些时间的标准传输格式为时间戳,所以封装一个方法如下
//filename global.js
Date.prototype.format = function(format) {
/*
* eg:format="YYYY-MM-dd hh:mm:ss";
* new Date().format("yyyy.MM.dd");
*/
var o = {
"M+" :this.getMonth() + 1, // month
"d+" :this.getDate(), // day
"h+" :this.getHours(), // hour
"m+" :this.getMinutes(), // minute
"s+" :this.getSeconds(), // second
"q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
"S" :this.getMilliseconds()
// millisecond
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "")
.substr(4 - RegExp.$1.length));
}
for ( var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
: ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}
使用示例
new Date().format("yyyy-MM-dd hh:mm:ss");
2022-12-02 22:00:00
new Date().format("yyyy.MM.dd hh:mm:ss");
2022.12.02 22:00:00
new Date().format("yyyy-MM-dd");
2022-12-02
new Date().format("yyyy.MM.dd");
2022.12.02
new Date().format('hh:mm:ss')
22:00:00
new Date(1669992855111).format('yyyy-MM-dd hh:mm:ss')
2022-12-02 22:54:15
在H5、小程序中都可以使用,比如在uniapp的main.js文件中就可以引用上面的global.js,这样全局即可使用
//filename main.js
require('global.js');
网友评论