我已经创建了这个脚本,以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.padZero= function(len){
var s= String(this), c= '0';
len= len || 2;
while(s.length < len) s= c + s;
return s;
}
/ /使用:
(function(){
var myDate= new Date(), myDateString;
myDate.setDate(myDate.getDate()+10);
myDateString= [myDate.getDate().padZero(),
(myDate.getMonth()+1).padZero(),
myDate.getFullYear()].join('/');
alert(myDateString);
})()
/* value: (String)
09/09/2010
*/
另一种选择,使用内置函数来填充(但会导致相当长的代码!):
myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
+ '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
+ '/' + myDate.getFullYear();
// '12/06/2017'
另一个,用正则表达式操作字符串:
var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');
// '2017/06/12'
但是要注意的是,在开头显示年份,在结尾显示日期。