直接上代码吧
function getDate() {
let now = new Date();
let y = now.getFullYear();
let month = (now.getMonth() + 1) < 10 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1;
let d = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
let h = now.getHours() < 10 ? "0" + now.getHours() : now.getHours()
let m = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes() ;
let w = "星期" + "日一二三四五六".charAt(now.getDay());
return (y + "/" + month + "/" + d + " " + h + ":" + m + " " + w);
}
// 调用
let time = getDate();
console.log(time); // 2019/05/24 17:11 星期五
console.log(typeof time); // string
代码解释:上面的代码中,用到了三目运算,作用是解决日期的格式问题,当月份、日期、小时、分这四个值小于10的时候,是输出个位数的,为了格式统一规范,所以这里作了简单处理,比如2019-5-24 8:33 星期五,这样不是很好看,处理过后是这样显示的:2019-05-24 08:33 星期五。如果不需要这样显示的话,把上面的代码的三目运算去掉就可以的了。注意返回的是string类型的值。
博客给出处理JS日期时间格式的代码,代码中运用三目运算解决日期格式问题。当月份、日期、小时、分小于10时,原格式输出个位数不美观,处理后格式更规范。若无需此效果,去掉三目运算即可,返回值为string类型。

532

被折叠的 条评论
为什么被折叠?



