我已经创建了这个脚本,以dd/mm/yyyy的格式提前计算10天的日期:

var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();

我需要通过将这些规则添加到脚本中,使日期在日期和月份组件上以前导零出现。我好像不能让它工作。

if (MyDate.getMonth < 10)getMonth = '0' + getMonth;

and

if (MyDate.getDate <10)get.Date = '0' + getDate;

如果有人能告诉我在哪里插入这些脚本,我会非常感激。


当前回答

这里有一个非常简单的例子,你可以如何处理这种情况。

var mydate = new Date(); var month = (mydate.getMonth(). tostring()。长度< 2 ?“0”+ mydate.getMonth () .toString (): mydate.getMonth ()); var date = (mydate.getDate(). tostring()。长度< 2 ?“0”+ mydate.getDate () .toString (): mydate.getDate ()); var year = mydate.getFullYear(); console.log(“格式Y-m-d:”+“-”+月+“-”+日期); Y / m / d: console.log(“格式”,年+ " +月+ " +日期);

其他回答

你可以定义一个"str_pad"函数(在php中):

function str_pad(n) {
    return String("00" + n).slice(-2);
}

我将这个问题的正确答案包装在一个函数中,该函数可以添加多个前导零,但默认为添加1个零。

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));
}

对于只处理数字且不超过2位数的情况,这也是一种方法:

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

我要做的是,创建我自己的自定义Date助手,看起来像这样:

var DateHelper = { addDays : function(aDate, numberOfDays) { aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays return aDate; // Return the date }, format : function format(date) { return [ ("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes ("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes date.getFullYear() // Get full year ].join('/'); // Glue the pieces together } } // With this helper, you can now just use one line of readable code to : // --------------------------------------------------------------------- // 1. Get the current date // 2. Add 20 days // 3. Format it // 4. Output it // --------------------------------------------------------------------- document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));

(也可以参看这把小提琴)

 let date = new Date();
 let dd = date.getDate();//day of month

 let mm = date.getMonth();// month
 let yyyy = date.getFullYear();//day of week
 if (dd < 10) {//if less then 10 add a leading zero
     dd = "0" + dd;
   }
 if (mm < 10) {
    mm = "0" + mm;//if less then 10 add a leading zero
  }

我认为这个解决方案更简单,也更容易记住:

var MyDate = new Date(); var day = MyDate.getDate() + 10;//提前10天 var month = MyDate.getMonth() + 1;//由于月份从0开始,我们应该给它加1 var year = MyDate.getFullYear(); day = checkDate(天); 月= checkDate(月); 函数checkDate(我){ 如果(i < 10){ I = '0' + I; } 返回我; } console.log(“${月}/{天}/{一}’美元);