前端常用日期格式转换dateFormate.js

本文介绍了前端开发中常用的日期格式转换库`dateFormate.js`,包括基本的日期格式化和简单的日期计算功能。虽然`moment.js`更为强大,但`dateFormate.js`提供了一个轻量级的解决方案。
摘要由CSDN通过智能技术生成

dateFormat.js 常用日期格式转换


const WEEK_ARR = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

export class DateFormat {
   
    date
    constructor(date = new Date()) {
   
        this.date = this.getDate(date)
    }

    getTimestamp(days) {
   
        return days * 24 * 60 * 60 * 1000
    }

    add(count, type = 'day') {
   
        switch (type) {
   
            case 'day':
                this.date = new Date(+this.date + this.getTimestamp(count))
                break
            case 'week':
                this.date = new Date(+this.date + this.getTimestamp(count * 7))
                break
            case 'month':
                const thisMonth = this.date.getMonth()
                // const year = (thisMonth + count)/12 >> 0
                // const month = (thisMonth + count) % 12
                // this.date.setYear(this.date.getFullYear()+year)
                this.date.setMonth(thisMonth + count)
                break
            default:
        }
        return this
    }

    /*
     * @date  可以是时间戳,字符串,Date对象
     */
    getDate(date) {
   

        if(!date) {
   
            return new Date()
        }

        if(date instanceof Date ) {
   
            return date
        }

        if(isNaN(date) && typeof date === 'string') {
   
            // 2017-01 || 2017/1
            if(/^\d{4}-\d{2}$/.test(date) || /^\d{4}\/\d{2}$/.test(date)) {
   
                date = `${
     date}-01`
            }
            return new Date(date.replace(/-/g, '/'))
        }

        if(typeof +date === 'number') {
   
            return new Date(date)
        }
    }

    isSame(time, type = 'day') {
   
        if(type === 'day') {
   
            return this.format('YYYY-MM-DD') === time.format
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值