获取两个日期之间的天数

参考链接:https://www.cnblogs.com/cckui/p/10785037.html

function formatEveryDay(start, end) {
    let dateList = []; 
    var startTime = new Date(start)
    var endTime = new Date(end)
    console.log(startTime,"startTime");
    console.log(endTime,"endTime");
    while ((endTime - startTime) >= 0) {
        var year = startTime.getFullYear();
        var month = startTime.getMonth() + 1 < 10 ? '0' + (startTime.getMonth() + 1) : startTime.getMonth() + 1;
        var day = startTime.getDate().toString().length == 1 ? "0" + startTime.getDate() : startTime.getDate();
        dateList.push(year + "-" + month + "-" + day); 
        startTime.setDate(startTime.getDate() + 1);
    }
    return dateList;
}
let a = new Date("2021/01/14").getTime();
let b = new Date("2021/03/15").getTime();
console.log(formatEveryDay(a,b));

效果:

["2021-01-14", "2021-01-15", "2021-01-16", "2021-01-17", "2021-01-18", "2021-01-19", "2021-01-20", "2021-01-21", "2021-01-22", "2021-01-23", "2021-01-24", "2021-01-25", "2021-01-26", "2021-01-27", "2021-01-28", "2021-01-29", "2021-01-30", "2021-01-31", "2021-02-01", "2021-02-02", "2021-02-03", "2021-02-04", "2021-02-05", "2021-02-06", "2021-02-07", "2021-02-08", "2021-02-09", "2021-02-10", "2021-02-11", "2021-02-12", "2021-02-13", "2021-02-14", "2021-02-15", "2021-02-16", "2021-02-17", "2021-02-18", "2021-02-19", "2021-02-20", "2021-02-21", "2021-02-22", "2021-02-23", "2021-02-24", "2021-02-25", "2021-02-26", "2021-02-27", "2021-02-28", "2021-03-01", "2021-03-02", "2021-03-03", "2021-03-04", "2021-03-05", "2021-03-06", "2021-03-07", "2021-03-08", "2021-03-09", "2021-03-10", "2021-03-11", "2021-03-12", "2021-03-13", "2021-03-14", "2021-03-15"]

 时间戳转换为datetime格式:

    add0(m){//添加0
      return m < 10 ? '0' + m : m;
    },
    format(shijianchuo){
      //shijianchuo是整数,否则要parseInt转换
      var time = new Date(shijianchuo);
      var y = time.getFullYear();
      var m = time.getMonth()+1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      return y+'-'+this.add0(m)+'-'+this.add0(d)+' '+this.add0(h)+':'+this.add0(mm)+':'+this.add0(s);
    }

datetime格式:2021-03-17 23:59:59

 

 

posted @ 2021-03-15 21:02  古墩古墩  Views(167)  Comments(0Edit  收藏  举报