需求:给定一个时间戳,获取这个时间戳上个月或者下个月的时间戳?
难点是不确定月份,所以这里先获取月份,再判断的(具体看代码注释都有)。时间戳转年月日就不贴出来了,网上太多了
用法:
// 上个月:
this.time = this.getPreviousMonthTimestamp(Number(new Date()), 0)
// 下个月:
this.time = this.getPreviousMonthTimestamp(Number(new Date()), 1)
代码:
// 获取上个月或者下个月的时间戳
getPreviousMonthTimestamp(timestamp, addType) {
// 将时间戳转换为Date对象
let date = new Date(timestamp);
// 获取当前月份
let currentMonth = date.getMonth();
if (addType === 0) {
// 判断当前月份是否为1月,如果是,则将上个月的月份设置为去年的12月
if (currentMonth === 0) {
currentMonth = 11; // 0表示1月,因此需要将月份减1
date = new Date(date.getFullYear() - 1, currentMonth, 1); // 设置日期为去年的12月1日
} else {
// 否则,将上个月的月份设置为当前月份减1
currentMonth--;
date = new Date(date.getFullYear(), currentMonth, 1); // 设置日期为上个月的1号
}
} else {
// 判断当前月份是否为12月,如果是,则将下个月的月份设置为去明年的1月
if (currentMonth === 11) {
currentMonth = 0; // 0表示1月,因此需要将月份减1
date = new Date(date.getFullYear() + 1, currentMonth, 1); // 设置日期为去年的12月1日
} else {
// 否则,将下个月的月份设置为当前月份加1
currentMonth++;
date = new Date(date.getFullYear(), currentMonth, 1); // 设置日期为下个月的1号
}
}
// 获取上个月的时间戳
let previousMonthTimestamp = date.getTime();
return previousMonthTimestamp;
}