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

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


当前回答

 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
  }

其他回答

你可以使用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

您可以使用三元运算符将日期格式化为“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将有助于更容易理解。

正如@John Henckel所建议的,开始使用toISOString()方法会让事情变得更简单

const dateString = new Date().toISOString().split('-'); const year = [0]; const month = [1]; const day = dateString[2].split('T')[0]; console.log(“${一},{月}-{天}’美元);

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

您可以提供选项作为参数来格式化日期。第一个参数用于区域设置(您可能不需要),第二个参数用于选项。 欲了解更多信息,请访问 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));