请问各位,小程序中怎样根据当前时间拿到上个月的月初和月末日期?
问题描述:
微信小程序中怎样根据当前时间拿到上个月的月初和月末日期?
没有思路,请问各位怎样实现
答
一定要注意跨年的问题哦。下面的这个例子跨年是没有问题的。
let today = new Date();
temp = new Date(`${today.getFullYear()}-${today.getMonth()+1}`);
preMonthLastDay = new Date(temp.getTime()-24*60*60*1000);
preMonthFirstDay = new Date(`${preMonthLastDay.getFullYear()}-${preMonthLastDay.getMonth()+1}`);
console.log(preMonthFirstDay.toLocaleDateString(),preMonthLastDay.toLocaleDateString());
//输出 2021/8/1 2021/8/31
答
var now = new Date(); //当前日期
var nowMonth = now.getMonth() -1; //当前月 减 1 为上月
var nowYear = now.getFullYear(); //当前年
//上月的开始时间
var monthStartDate = new Date(nowYear, nowMonth, 1);
//上月的结束时间
var monthEndDate = new Date(nowYear, nowMonth+1, 0);
这就是我抄的 百度很多啊 https://www.cnblogs.com/mmzuo-798/p/13306655.html
答
这样写可以获取到,虽然不是最简的方式。
这样写可以获取到,虽然不是最简的方式。
答
function getLastMonthDate (d) {
const date = new Date(d)
const year = date.getMonth() == 0 ? date.getFullYear() - 1 : date.getFullYear() //获取上月年份,如果当前月是一月则为去年
let month = date.getMonth() == 0 ? '12' : date.getMonth() //date.getMonth()获取上月月份,0代表十二月
month = month < 10 ? "0" + month : month
date.setDate(0) // 设置日期为上月最后一天
let day = date.getDate() //获取最后一天日期
day = day < 10 ? "0" + day : day
return [year + '-' + month + '-' + '01',year + '-' + month + '-' + day]
}
console.log(getLastMonthDate('2021-1')) //[ '2020-12-01', '2020-12-31' ]
答
获取当前月份 ,月份-1 然后 然后 判断 其月份 。月初都是 1号。月末就得根据 大小月来判断 ,2月的话还得分平年 闰年