简体   繁体   中英

adding leading zero if number is < 10

Need extra '0' in front of day, hour, minute, second numbers when there are < 10.
Please help! Thanks!!

            dateDiff: function(date1, date2){
                var diff = {}
                var tmp = date2 - date1;

                tmp = Math.floor(tmp/1000);
                diff.sec = tmp % 60;
                tmp = Math.floor((tmp-diff.sec)/60);
                diff.min = tmp % 60; 
                tmp = Math.floor((tmp-diff.min)/60);
                diff.hour = tmp % 24;
                tmp = Math.floor((tmp-diff.hour)/24);
                diff.day = tmp;

                return diff;
            },

Try this function

function addZero(number)
{
 if(number<10)
    return "0"+number;
 else
    return number;
}

You can use the slice method

diff.sec = tmp % 60;
if( diff.sec < 10 ){
    diff.sec = ("0" + diff.sec).slice(-2);
}

JSFiddle with sample value

 var test = 9; if( test < 10 ){ test = ("0" + test).slice(-2); } console.log(test); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM