// 获取上个月的日期对象
function getLastMonthDate() {
const today = new Date();
const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
return lastMonth;
}
// 格式化上个月的日期为 YYYY-MM-DD 格式
function formatLastMonthDate() {
const lastMonthDate = getLastMonthDate();
const year = lastMonthDate.getFullYear();
const month = String(lastMonthDate.getMonth() + 1).padStart(2, '0');
const day = String(lastMonthDate.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
console.log(formatLastMonthDate());
getLastMonthDate
函数:获取当前日期,然后通过 new Date(year, month - 1, date)
的方式创建一个表示上个月同一日期的日期对象。注意月份是从 0 开始计数的(即 0 表示 1 月),所以需要减去 1。
formatLastMonthDate
函数:将上个月的日期格式化为 YYYY-MM-DD
的字符串形式。使用 padStart
方法确保月份和日期都是两位数。
console.log(formatLastMonthDate())
:输出格式化后的上个月日期。
如果你只需要获取上个月的时间信息而不需要具体日期,可以根据需求调整代码。
上一篇:flexible.js 怎么使用
下一篇:js array排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站