请问各位,小程序中怎样根据当前时间拿到上个月的月初和月末日期?

微信小程序中怎样根据当前时间拿到上个月的月初和月末日期?
没有思路,请问各位怎样实现

一定要注意跨年的问题哦。下面的这个例子跨年是没有问题的。


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

img


这样写可以获取到,虽然不是最简的方式。

获取当前月份 ,月份-1 然后 然后 判断 其月份 。月初都是 1号。月末就得根据 大小月来判断 ,2月的话还得分平年 闰年