我已经创建了这个脚本,以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;
如果有人能告诉我在哪里插入这些脚本,我会非常感激。
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
您可以提供选项作为参数来格式化日期。第一个参数用于区域设置(您可能不需要),第二个参数用于选项。
欲了解更多信息,请访问
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));
另一种选择,使用内置函数来填充(但会导致相当长的代码!):
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'
但是要注意的是,在开头显示年份,在结尾显示日期。