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

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


当前回答

你可以简单地使用:

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();

其他回答

试试这个:http://jsfiddle.net/xA5B7/

var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
             + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
             + MyDate.getFullYear();

编辑:

为了解释,.slice(-2)给出了字符串的最后两个字符。

所以无论如何,我们都可以在日期或月份后加上“0”,只要求最后两个,因为这两个总是我们想要的。

所以如果MyDate.getMonth()返回9,它将是:

("0" + "9") // Giving us "09"

加上。slice(-2)就得到了最后两个字符:

("0" + "9").slice(-2)
"09"

但如果MyDate.getMonth()返回10,它将是:

("0" + "10") // Giving us "010"

所以加上.slice(-2)会得到最后两个字符,或者:

("0" + "10").slice(-2)
"10"

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

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

toISOString可以得到前导0

const currentdate = new Date(); const date = new date (date. utc (currentdate.getFullYear(), (currentdate.getMonth()),currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), currentdate.getSeconds())); //你可以传递YY, MM, DD //op: 2018-03-01 //i have passed YY, MM, DD, HH, Min, Sec // op: 2021-06-09T12:14:27.000Z console.log (date.toISOString ());

输出将类似于此:2021-06-09T12:14:27.000Z

添加一些填充以允许前导零(在需要的地方),并使用所选的分隔符作为字符串进行连接。

Number.prototype.padLeft = function(base,chr){
        var  len = (String(base || 10).length - String(this).length)+1;
        return len > 0? new Array(len).join(chr || '0')+this : this;
    }

var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');