js输出当前时间以及上个月时间 格式为yyyy-MM-dd
以下是JavaScript代码,可以输出当前时间以及上个月时间,格式为yyyy-MM-dd:
// 获取当前时间
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
// 格式化当前时间
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
var currentDate = year + '-' + month + '-' + day;
// 获取上个月时间
var lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);
var lastYear = lastMonth.getFullYear();
var lastMonthValue = lastMonth.getMonth() + 1;
var lastMonthDay = lastMonth.getDate();
// 格式化上个月时间
if (lastMonthValue < 10) {
lastMonthValue = '0' + lastMonthValue;
}
if (lastMonthDay < 10) {
lastMonthDay = '0' + lastMonthDay;
}
var lastMonthDate = lastYear + '-' + lastMonthValue + '-' + lastMonthDay;
// 输出结果
console.log('当前时间:' + currentDate);
console.log('上个月时间:' + lastMonthDate);
这段代码首先获取当前时间,然后格式化为yyyy-MM-dd的形式。接着获取上个月时间,同样格式化为yyyy-MM-dd的形式。最后输出结果
原文地址: https://www.cveoy.top/t/topic/fGbj 著作权归作者所有。请勿转载和采集!