在实际做项目的过程中,时间格式的处理是常用的,比如把"/"替换成"-"且去掉后面的时间戳只显示日期,这个实现对于很多人来说是信手拈来了,先说一版简单的实现
//res.date从服务器获取到的数据
const d = new Date(res.date);
const year = d.getFullYear();
const date = d.getDate();
const month = d.getMonth() + 1;
return `${year}-${month}-${date}`;
因为要复用所以抽成函数,但是有没有优化的空间呢
function getPrettyDate(date){
const d = new Date(date);
const year = d.getFullYear();
const date = d.getDate();
const month = d.getMonth() + 1;
return `${year}-${month}-${date}`;
}
我在用vscode的时候有一个非常讨厌的地方,就是写完函数之后光标不会自动定位到括号里面,导致我要用鼠标点一下然后写参数,有没有不用传参的办法,这样就能偷懒了
//常规的调用方式
getPrettyDate("2021/06/18 9:44:30");
getPrettyDate("2021/06/18T9:44:30");
//期待的调用方式
getPrettyDate();
当然不传参并不是什么也不传,而是不在括号里面传参,一番思索我把问题的重点放在了调用者上面,函数的调用者在函数内部是this,直接把this当参数就行了
function getPrettyDate(){
const d = new Date(this);
const year = d.getFullYear();
const date = d.getDate();
const month = d.getMonth() + 1;
return `${year}-${month}-${date}`;
}
//这是我们要实现的调用方式
"2021/06/18".getPrettyDate();
可是问题来了,"2021/06/18"并没有这个方法,我们得想办法加上,"2021/06/18"是字符串对象可以直接调用原型里面的方法,所以我们加在String.prototype上面
String.prototype.getPrettyDate = function(){
const d = new Date(this);
const year = d.getFullYear();
const date = d.getDate();
const month = d.getMonth() + 1;
return `${year}-${month}-${date}`;
}
"2021/06/18".getPrettyDate();
大功告成,但是如果服务器传过来的是数字呢
Number.prototype.getPrettyDate = function(){
const d = new Date(this);
const year = d.getFullYear();
const date = d.getDate();
const month = d.getMonth() + 1;
return `${year}-${month}-${date}`;
}
(1623981685073).getPrettyDate();
当然有一种万能的方法,直接放在Object.prototype里面
Object.prototype.getPrettyDate = function(){
const d = new Date(this);
const year = d.getFullYear();
const date = d.getDate();
const month = d.getMonth() + 1;
return `${year}-${month}-${date}`;
}
(1623981685073).getPrettyDate();
"2021/06/18".getPrettyDate();