常用的時間處理(Date => String)

var timer = {
    /**
     * 補足 0
     * @param { Number | String } num 
     * @returns { String }
     */
    padLeftZero: function(num) {
        // es6 中可用 padStart() 來完成補足
        return ('0' + num).slice(-2);
    },

    /**
     * 處理成想要的日期字符串
     * @param { Date | String} date 
     * @param { String } formate 
     * @returns { String }
     */
    handle2String: function(date, formate) {
        if (date === null || date.length === 0) return '';
        
        var tempDate = new Date(date);

        if (/(y+)/.test(formate)) formate = formate.replace(RegExp.$1, (tempDate.getFullYear() + '').substring(4 - RegExp.$1.length));
        
        var o = {
            'M+': tempDate.getMonth() + 1,
            'd+': tempDate.getDate(),
            'h+': tempDate.getHours(),
            'm+': tempDate.getMinutes(),
            's+': tempDate.getSeconds(),
        }

        for (var key in o) {
            if (!o.hasOwnProperty(key)) continue;

            if (new RegExp(`(${key})`).test(formate)) formate = formate.replace(RegExp.$1, this.padLeftZero(o[key]));
        }

        return formate;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章