JavaScript js获取当前日期上一个月、下一个月并处理特殊月2月问题
js获取当前日期上一个月、下一个月并处理特殊月2月问题
·
/**
* 获取当前日期的上一个月
* 对日期做处理,例如获取2022-03-28,29,30,31,都会返回2022-02-28
* @date 格式为yyyy-mm-dd hh:mm:ss 星期x的日期,如:2022-07-08 15:45:45 星期三
*/
// 获取当前日期的上一个月
function getlastMonth() {
let now = new Date();
// 当前年月的日
let nowDate = now.getDate();
//当前月份完整日期 (Thu Jul 07 2022 12:03:37 GMT+0800 (中国标准时间))
let lastMonth = new Date(now.getTime());
// 设置上一个月(这里不需要减1) getMonth()返回表示月份的数字 setMonth()设置月份参数
lastMonth.setMonth(lastMonth.getMonth());
// 设置为0,默认为当前月的最后一天
lastMonth.setDate(0);
// 上一个月的天数
let daysOflastMonth = lastMonth.getDate();
// 设置上一个月的日期,如果当前月的日期大于上个月的总天数,则为最后一天
// 例如当前是3月31,而2月只有28或29天,则取2月的最后一天
lastMonth.setDate(nowDate > daysOflastMonth ? daysOflastMonth : nowDate);
//调用格式化日期函数
lastMonth = getNowFormatDate(lastMonth);
return lastMonth;
}
console.log(getlastMonth()); //2022-06-08 15:59:58 星期三
日期格式化函数
//格式化日期函数
function getNowFormatDate(date) {
// let date = new Date() //获取当前完整日期
let year = date.getFullYear(), // 返回日期的年
month = date.getMonth() + 1, // 月份 返回的月份小1个月 记得月份+1
d = date.getDate(), // 返回的是 几号
hour = date.getHours(), // 时
minute = date.getMinutes(), // 分
second = date.getSeconds(), // 秒
w = date.getDay(), // 周一返回的是 1 周六返回的是 6 但是 周日返回的是 0
week = [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六",
];
month = month < 10 ? "0" + month : month;
d = d < 10 ? "0" + d : d;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
return `${year}-${month}-${d} ${hour}:${minute}:${second} ${week[w]}`;
}
/**
* 获取当前日期的下一个月 (这里没用到日期格式化函数)
* 对日期做处理,例如获取2022-01-28,29,30,31,都会返回2022-02-28
* @date 格式为yyyy-mm-dd
*/
// 获取当前日期的下一个月
function getNowdate() {
let now = new Date(), //获取当前时间
year = now.getFullYear(), //获取当前时间的年份
month = now.getMonth(), //获取当前时间的月份
day = now.getDate(), //获取当前时间的日
newYear = year,
nextMonth = parseInt(month + 2), //获取当前月份的一个月以后的月份
currentDay = day;
/* days = new Date(year, month, 0) //将获取到的年月赋值给days
days = days.getDate() //获取当前年月的日 */
//考虑到12月要是获取一个月以后,就是一月,年份需要加一 ,一年没有13月,所以%12,取得来年1月
if (nextMonth > 12) {
newYear = parseInt(newYear) + 1;
nextMonth = parseInt(nextMonth) % 12;
}
let nextDay = new Date(newYear, nextMonth, 0); //将获取到的年月赋值给nextDay
nextDay = nextDay.getDate(); //获取当前月份的一个月以后的日
/* 获取了当前年份的日和1个月以后的日,为的就是判断如果前一个月是有31号,
后一个月没有,就将一个月以后的日期取到,赋值给currentDay */
currentDay = currentDay > nextDay ? nextDay : currentDay;
nextMonth = nextMonth < 10 ? "0" + nextMonth : nextMonth;
currentDay = currentDay < 10 ? "0" + currentDay : currentDay;
return `${newYear}-${nextMonth}-${currentDay}`;
}
console.log(getNowdate()); // 2022-08-08
到此结束。
更多推荐
所有评论(0)