Javascript日期格式化指定格式的字符串实现

代码部分

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

如果你觉得这篇博客有用,那就点击右下角的【推荐】支持一下我把:D
你还可以【关注我】,我会经常更新博客的 ;D
原文地址:https://www.cnblogs.com/rocketRobin/p/6370801.html