Javascript add leading zeroes to date

后端 未结 25 1871
执笔经年
执笔经年 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

    I wrapped the correct answer of this question in a function that can add multiple leading zero's but defaults to adding 1 zero.

    function zeroFill(nr, depth){
      depth = (depth === undefined)? 1 : depth;
    
      var zero = "0";
      for (var i = 0; i < depth; ++i) {
        zero += "0";
      }
    
      return (zero + nr).slice(-(depth + 1));
    }
    

    for working with numbers only and not more than 2 digits, this is also an approach:

    function zeroFill(i) {
        return (i < 10 ? '0' : '') + i
      }
    

提交回复
热议问题