js 日期格式化

let DateFormat = {
    date: new Date(),
    YEAR: 0,
    get YEAR(){
        return new Date().getFullYear()
    },
    MONTH: 0,
    get MONTH(){
        return new Date().getMonth() + 1
    },
    WEEK: 0,
    get WEEK(){
        return new Date().getDay()
    },
    DATE: 0,
    get DAY(){
        return new Date().getDate()
    },
    HOUER: 0,
    get HOUER(){
        return new Date().getHours()
    },
    MINUTE: 0,
    get MINUTE(){
        return new Date().getMinutes()
    },
    SECOND: 0,
    get SECOND(){
        return new Date().getSeconds()
    },
    SECONDS: 0,
    get SECONDS(){
        return Math.floor(Date.now() / 1000)
    },
    MILLISECOND: 0,
    get MILLISECOND(){
        return new Date().getMilliseconds()
    },
    MILLISECONDS: 0,
    get MILLISECONDS(){
        return Date.now()
    },
    format(reg, dateObj){
        let str = reg
        str = str.replace(/yyyy|YYYY/, dateObj.getFullYear())

        let month = dateObj.getMonth() + 1
        str = str.replace(/MM/, month < 10 ? '0' + month : month)
        str = str.replace(/M/, month)

        let date = dateObj.getDate()
        str = str.replace(/dd|DD/, date < 10 ? '0' + date : date)
        str = str.replace(/d|D/, date)

        let hour = dateObj.getHours()
        str = str.replace(/hh|HH/, hour < 10 ? '0' + hour : hour)
        str = str.replace(/h|H/, hour)

        let week = dateObj.getDay()
        str = str.replace(/hh|HH/, hour < 10 ? '0' + hour : hour)
        str = str.replace(/h|H/, hour)

        let minute = dateObj.getMinutes()
        str = str.replace(/mm/, minute < 10 ? '0' + minute : minute)
        str = str.replace(/m/, minute)

        let second = dateObj.getSeconds()
        str = str.replace(/ss|SS/, second < 10 ? '0' + second : second)
        str = str.replace(/s|S/, second)

        let milliSecond = dateObj.getMilliseconds()
        str = str.replace(/nnn|NNN/, milliSecond < 10 ? '00' + milliSecond :
 milliSecond < 100 ? '0' + milliSecond : milliSecond)
        str = str.replace(/n|N/, milliSecond)
        return str
    }
}

 使用说明

  当前时间的 年/月/日/时/分/秒/

  DateFormat.YEAR/MONTH/DATE/HOUER/MINUTE/SECOND

  格式化日期,DateFormat.format(reg, Date) reg日期模板,Date Date对象

reg说明

yyyy/YYYY 年  MM月(填充0,下同)M月  dd/DD/d/D 日 hh/HH/h/H 时 mm/m 分 ss/SS s/S 秒 nnn/NNN/n/N毫秒

  例如:

//不带参数的日期,默认为当前时间

console.log(DateFormat.format('yyyy/M/d hh:mm:ss nnn', new Date()))

//传入带时间戳参数的日期对象

console.log(DateFormat.format('yyyy/M/d hh:mm:ss nnn', new Date(1538901361498)))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值