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

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


当前回答

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

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

其他回答

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

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

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}`;

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

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

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

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

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