Javascript add leading zeroes to date

后端 未结 25 2410
执笔经年
执笔经年 2020-11-22 02:50

I\'ve created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:

var MyDate = new Date();
var MyDateString = new Date();
M         


        
25条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 03:21

    The following aims to extract configuration, hook into Date.protoype and apply configuration.

    I've used an Array to store time chunks and when I push() this as a Date object, it returns me the length to iterate. When I'm done, I can use join on the return value.

    This seems to work pretty fast: 0.016ms

    // Date protoype
    Date.prototype.formatTime = function (options) {
        var i = 0,
            time = [],
            len = time.push(this.getHours(), this.getMinutes(), this.getSeconds());
    
        for (; i < len; i += 1) {
            var tick = time[i];
            time[i] = tick < 10 ? options.pad + tick : tick;
        }
    
        return time.join(options.separator);
    };
    
    // Setup output
    var cfg = {
        fieldClock: "#fieldClock",
        options: {
            pad: "0",
            separator: ":",
            tick: 1000
        }
    };
    
    // Define functionality
    function startTime() {
        var clock = $(cfg.fieldClock),
            now = new Date().formatTime(cfg.options);
    
        clock.val(now);
        setTimeout(startTime, cfg.options.tick);
    }
    
    // Run once
    startTime();
    

    demo: http://jsfiddle.net/tive/U4MZ3/

提交回复
热议问题