js封装日期+时间+星期的函数

博客给出处理JS日期时间格式的代码,代码中运用三目运算解决日期格式问题。当月份、日期、小时、分小于10时,原格式输出个位数不美观,处理后格式更规范。若无需此效果,去掉三目运算即可,返回值为string类型。

直接上代码吧

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类型的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值