封装时间格式


/*
 * params: 任意参数分割日期,默认汉字格式
 * return: 返回指定格式日期
 */
~ function() {
	// 封装格式日期函数
    function formatTime(format = 'cn') { //格式默认为中文
        time = this.match(/\d+/g);//将日期拆分成数组
        let template = format === 'cn' ? "{0}年{1}月{2}日 {3}时{4}分{5}秒" : `{0}${format}{1}${format}{2} {3}:{4}:{5}`;//判断日期模板
        return template = template.replace(/\{(\d+)\}/g, (content, $1) => { //将模板中指定内容替换
            let newtime = time[$1] || "00";// 自动将缺少的时间变为00
            return newtime = newtime.length < 2 ? "0" + newtime : newtime;//将小于两位的时间前面加一个字符串0
        });
    };
    String.prototype['formatTime'] = formatTime;//挂载到字符串原型
}();
//测试
let time1='2020年9月22号 12:22:33';
console.log(time1.formatTime());//'2020年09月22日 12时22分33秒'
let time2='2020年9月22号';
console.log(time2.formatTime());//'2020年09月22日 00时00分00秒'
let time3='2020年9月22号 12:22:33';
console.log(time3.formatTime('-'));//'2020-09-22 12:22:33'
let time4='2020年9月22号';
console.log(time4.formatTime('+'));//'2020+09+22 00:00:00'
let time5='2020-09-22 12:22:33';
console.log(time5.formatTime());//'2020年09月22日 12时22分33秒'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值