我已经创建了这个脚本,以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;
如果有人能告诉我在哪里插入这些脚本,我会非常感激。
一个简单的dateformat库拯救了我的生命(GitHub):
Node.js: var dateFormat = require(" dateFormat ");
ES6: import dateFormat from dateFormat;
const now = new Date(); // consider 3rd of December 1993
const full = dateFormat(today, "yyyy-mm-dd"); // 1993-12-03
const day = dateFormat(today, "dd"); // 03
const month = dateFormat(today, "mm"); // 12
const year = dateFormat(today, "yyyy"); // 1993
值得一提的是,它支持广泛的掩模选项。
你可以使用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