1. 程式人生 > >react時間戳轉換成需要格式

react時間戳轉換成需要格式

後端返回前端日期時間,一般給你的都是時間戳,然後前端展示需要轉換成需要格式。以下是我開發中常遇到需要轉換成的格式,看程式碼。

class DateApi {
    /**
     * 將輸入的毫秒字串or毫秒數轉換成指定的字串格式
     * @param {string} msStr 毫秒字串 or 毫秒數
     * @param {string} format yyyy-MM-dd or yyyy-MM-dd hh:mm:ss
     * @return {string} 轉換後的字串
     */
    static format(msStr, format) {
        const date = new Date(msStr / 1);
        let fmt = format;

        const obj = {
            'M+': date.getMonth() + 1, // 月份
            'd+': date.getDate(), // 日
            'h+': date.getHours(), // 小時
            'm+': date.getMinutes(), // 分
            's+': date.getSeconds(), // 秒
            'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
            S: date.getMilliseconds(), // 毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (String(date.getFullYear())).substr(4 - RegExp.$1.length));
        }
        const keys = Object.keys(obj);
        for (let i = 0; i <= keys.length; i += 1) {
            const k = keys[i];
            if (new RegExp(`(${k})`).test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (obj[k]) : ((`00${obj[k]}`).substr((String(obj[k])).length)));
            }
        }

        return fmt;
    }

    /**
     * 獲得傳入的秒字串msStr距離現在時間的字串,格式為 昨天 今天 明天 當前年3月4日 其餘2000-01-01
     * @param {string} msStr 毫秒字串
     * @return {string} 可以顯示用的字串
     */
    static format2(msStr, showYear) {
        let ms = new Date(DateApi.format(msStr, 'yyyy/MM/dd')).getTime() / 1000;
        const now = new Date(DateApi.format(new Date().getTime(), 'yyyy/MM/dd')).getTime() / 1000;
        ms = now - ms;

        const min = 60;
        const hour = 60 * min;
        const day = 24 * hour;

        if (ms === 0) {
            return '今天';
        }

        if (ms === day) {
            return '昨天';
        }

        if (ms === -day) {
            return '明天';
        }


        const date = new Date((msStr / 1));
        const nowYear = new Date().getFullYear();
        const year = date.getFullYear();
        const month = date.getMonth() + 1;

        if (showYear === false && year === nowYear) {
            return `${month}月${date.getDate()}日`;
        }

        return `${date.getFullYear()}年${month}月${date.getDate()}日`;
    }
    /**
    *獲取當前天數之前或者之後的日期
    *@num 之前或者之後多少天數 - 表示之前
    */
    static getDate(num, format) {
        const today = new Date();
        const targetday = today.getTime() + (1000 * 60 * 60 * 24 * num);
        const target = new Date();
        target.setTime(targetday);
        if (format) {
            return this.format(target.getTime(), format);
        }
        return target;
    }

}

module.exports = DateApi;