我已经创建了这个脚本,以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;

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


当前回答

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

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

其他回答

献给未来的人们(ECMAScript 2017及以后版本)

解决方案

"use strict"

const today = new Date()

const year = today.getFullYear()

const month = `${today.getMonth() + 1}`.padStart(2, "0")

const day = `${today.getDate()}`.padStart(2, "0")

const stringDate = [day, month, year].join("/") // 13/12/2017

解释

String.prototype。padStart(targetLength[, padString])在String中添加尽可能多的padString。这样目标的新长度就是targetLength。

例子

"use strict"

let month = "9"

month = month.padStart(2, "0") // "09"

let byte = "00000100"

byte = byte.padStart(8, "0") // "00000100"

尝试使用这个基本函数,不需要库

Date.prototype.CustomformatDate = function() {
 var tmp = new Date(this.valueOf());
 var mm = tmp.getMonth() + 1;
 if (mm < 10) mm = "0" + mm;
 var dd = tmp.getDate();
 if (dd < 10) dd = "0" + dd;
 return mm + "/" + dd + "/" + tmp.getFullYear();
};

下面是一个来自Mozilla Developer Network的Date对象文档的例子,它使用了一个自定义的“pad”函数,而不需要扩展Javascript的Number原型。他们给出的一个方便的例子是

function pad(n){return n<10 ? '0'+n : n}

下面是它在上下文中的用法。

/* use a function for the exact format desired... */
function ISODateString(d){
    function pad(n){return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
    + pad(d.getUTCMonth()+1)+'-'
    + pad(d.getUTCDate())+'T'
    + pad(d.getUTCHours())+':'
    + pad(d.getUTCMinutes())+':'
    + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

加上@modiX的答案,这是什么工作…不要让它空着

today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})

我将这个问题的正确答案包装在一个函数中,该函数可以添加多个前导零,但默认为添加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
  }