Js中取日期的前一天常用的方法有两种,分别如下:

1、利用setDate方法

  // date is Date type
        function getPreDate(date, preDays) {
            return new Date(date.setDate(date.getDate() - preDays));
        }

2、使用时间戳运算

//lebang2020.cn
 function getPreDate2(date, preDays) {
            return new Date(date.getTime() - 24 * 60 * 60 * 1000 * preDays);
        }

方法1在各大浏览器上新旧版本目前没有发现错误,不过还是推荐使用方法2,它比较严谨。

同理顺水推舟,我们现在可以按天计算各种场景了,比较加几天的日期,近30天的日期,后7天的日期等等。

这里还扩展了当月的最后一天,或者指定日期月份的最后一天,也是利用上述函数可以计算出来,代码如下:

//date is Date type
  function getLastDay(date) {
            return new Date( new Date(date.getFullYear(), date.getMonth(), 1).getTime() - 24 * 60 * 60 * 1000);
        }

可以使用如下代码测试上述函数

 function format(date) {
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            return y + '-' + m + '-' + d;
        }
        let a = getPreDate(new Date(), 5);
        let b = getPreDate(new Date(), 1);
        let aa = getPreDate2(new Date(), 5);
        let bb = getPreDate2(new Date(), 1);
        let last = getLastDay(new Date());

文章地址