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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值