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

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


当前回答

你可以使用string .slice()来提取字符串的一个部分,并将其作为一个新字符串返回,而不修改原始字符串:

const currentDate = new Date().toISOString().slice(0, 10) // 2020-04-16

或者你也可以使用像Moment.js这样的库来格式化日期:

const moment = require("moment")
const currentDate = moment().format("YYYY-MM-DD") // 2020-04-16

其他回答

const month = date.toLocaleDateString('en-US', { month: '2-digit' });
const day = date.toLocaleDateString('en-US', { day: '2-digit' });
const year = date.getFullYear();
const dateString = `${month}-${day}-${year}`;
function formatDate(jsDate){
  // add leading zeroes to jsDate when days or months are < 10.. 
  // i.e.
  //     formatDate(new Date("1/3/2013")); 
  // returns
  //    "01/03/2103"
  ////////////////////
  return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" + 
      ((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" + 
      jsDate.getFullYear();
}

您可以使用三元运算符将日期格式化为“if”语句。

例如:

var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();

So

(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())

将类似于if语句,其中如果getDate()返回的值小于10,则返回'0' +日期,如果大于10则返回日期(因为我们不需要加上前导0)。月份也是如此。

编辑: 忘记了getMonth以0开头,所以添加了+1来解释它。当然,您也可以只说d.g getmonth() < 9:,但我认为使用+1将有助于更容易理解。

加上@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
  }