Javascript日期格式化指定格式的字串實現

rocketrobin發表於2017-02-06

程式碼部分

TypeScript

 1   /**
 2      * format a Date object 
 3      * 將 Date 轉化為指定格式的String
 4      * @param {Date} date 源日期物件
 5      * @param {string} pattern 匹配模式
 6      * @returns {string} 格式化結果
 7      */
 8     fmtDate(date: Date, pattern: string) {
 9         return pattern
10             .replace(/yyyy/, date.getFullYear().toString())
11             .replace(/MM/, this.fillZero(date.getMonth() + 1, `l`, 2))
12             .replace(/dd/, this.fillZero(date.getDate(), `l`, 2))
13             .replace(/hh/, this.fillZero(date.getHours(), `l`, 2))
14             .replace(/mm/, this.fillZero(date.getMinutes(), `l`, 2))
15             .replace(/ss/, this.fillZero(date.getSeconds(), `l`, 2))
16             .replace(/S/, date.getMilliseconds().toString());
17     }

View Code

Javascript

 1     /**
 2      * format a Date object
 3      * 將 Date 轉化為指定格式的String
 4      * @param {Date} date 源日期物件
 5      * @param {string} pattern 匹配模式
 6      * @returns {string} 格式化結果
 7      */
 8     Aqua.prototype.fmtDate = function (date, pattern) {
 9         return pattern
10             .replace(/yyyy/, date.getFullYear().toString())
11             .replace(/MM/, this.fillZero(date.getMonth() + 1, `l`, 2))
12             .replace(/dd/, this.fillZero(date.getDate(), `l`, 2))
13             .replace(/hh/, this.fillZero(date.getHours(), `l`, 2))
14             .replace(/mm/, this.fillZero(date.getMinutes(), `l`, 2))
15             .replace(/ss/, this.fillZero(date.getSeconds(), `l`, 2))
16             .replace(/S/, date.getMilliseconds().toString());
17     };

View Code

 

補零函式 Typescript

    /**
     * fill 0 to a number
     * 數字補零
     * @param {number} src 源數字
     * @param {string} direction 方向 l r
     * @param {number} digit 補零後的總位數
     * @returns {string} 結果
     */
    fillZero(src: number, direction: string, digit: number) {
        let count: number = digit - src.toString().length;
        let os = new Array(count + 1).join(`0`);
        if (direction !== `r`) {
            return os + src;
        }
        return src + os;
    }

View Code

javascript

    /**
     * fill 0 to a number
     * 數字補零
     * @param {number} src 源數字
     * @param {string} direction 方向 l r
     * @param {number} digit 補零後的總位數
     * @returns {string} 結果
     */
    Aqua.prototype.fillZero = function (src, direction, digit) {
        var count = digit - src.toString().length;
        var os = new Array(count + 1).join(`0`);
        if (direction !== `r`) {
            return os + src;
        }
        return src + os;
    };

View Code

 

原理很簡單,就不寫了

歡迎檢視我的GitHub

https://github.com/rocketRobin/aqua-toolbox


相關文章