我已经创建了这个脚本,以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 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(“${月}/{天}/{一}’美元);

其他回答

还有另一种方法可以解决这个问题,在JavaScript中使用slice。

var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);

datestring返回日期,格式为您期望的:2019-09-01

另一种方法是使用dateformat库:https://github.com/felixge/node-dateformat

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

const dateString = new Date().toISOString().split('-'); const year = [0]; const month = [1]; const day = dateString[2].split('T')[0]; 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

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

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(“格式”,年+ " +月+ " +日期);

我找到了一个最短的方法:

 MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');

会给所有孤独的个位数加前导零吗