time.js 1.59 KB
/*
    yoho客服 im: 时间模块
    @author acgpiano
    Time.long() 返回年月日模块
    Time.short() 返回小时模块
*/

class Time {
    constructor(timestamp) {
        this.timestamp = new Date(timestamp);
    }

    // 日期格式化
    _format(timestamp, fmt) {
        let o = {
            'M+': timestamp.getMonth() + 1,
            'd+': timestamp.getDate(),
            'h+': timestamp.getHours(),
            'm+': timestamp.getMinutes(),
            's+': timestamp.getSeconds(),
            'q+': Math.floor((timestamp.getMonth() + 3) / 3),
            S: timestamp.getMilliseconds(),
        };

        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (timestamp.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ?
                    (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
            }
        }
        return fmt;
    }

    // 时间对比返回
    show() {
        let timef = this._format(this.timestamp, 'yyyy.MM.dd'),
            now = this._format(new Date(), 'yyyy.MM.dd');

        if (timef === now) {
            timef = this._format(this.timestamp, 'hh:mm');
        } else {
            timef = this._format(this.timestamp, 'yyyy.MM.dd hh:mm');
        }

        return this.render(timef);
    }

    render(timef) {
        return `<div class="chat-time">
                ${timef}
                </div>`;
    }
}

export function time(timestamp) {
    return new Time(timestamp);
}