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

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


当前回答

献给未来的人们(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"

其他回答

你可以简单地使用:

const d = new Date();
const day = `0${d.getDate()}`.slice(-2);

所以可以这样创建一个函数:

AddZero(val){
    // adding 0 if the value is a single digit
    return `0${val}`.slice(-2);
}

你的新代码:

var MyDate = new Date();
var MyDateString = new Date();

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

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

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(“${月}/{天}/{一}’美元);

你可以使用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
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();
}
var MyDate = new Date();
var MyDateString = '';
MyDate.setDate(MyDate.getDate());
var tempoMonth = (MyDate.getMonth()+1);
var tempoDate = (MyDate.getDate());
if (tempoMonth < 10) tempoMonth = '0' + tempoMonth;
if (tempoDate < 10) tempoDate = '0' + tempoDate;
MyDateString = tempoDate + '/' + tempoMonth + '/' + MyDate.getFullYear();