jq 获取2个日期之前的相差天数

2021-09-01    2021-09-30    29天
2021-09-01    2021-10-10    31天   为什么不是30天呢
function dateDiff(beginTime, endTime) {
        var aDate, oDate1, oDate2, days;

        aDate = beginTime.split("-");
        console.log(aDate);
        oDate1 = new Date(aDate[0], aDate[1], aDate[2]);
        console.log(oDate1);
        aDate = endTime.split("-");
        oDate2 = new Date(aDate[0], aDate[1], aDate[2]);
        days = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24);
        return days;
    }
阅读 2.5k
3 个回答

计算2个日期之间相差多少天

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
    
dayDif(new Date("2021-09-01"), new Date("2021-09-30"))
// Result: 29
dayDif(new Date("2021-09-01"), new Date("2021-10-10"))
// Result: 39

摘录至:20 个杀手级 JavaScript 单行代码

const diffDays = (d1, d2) => {
  const date1 = Date.parse(d1.toString());
  const date2 = Date.parse(d2.toString());
  const diff = (date2 - date1) / (3600 * 24 * 1000);
  return diff > 0 ? Math.floor(diff) : Math.ceil(diff || 0);
}

console.log(diffDays('2021-09-01', '2021-8-31'));
// -1 :第一天比第二天晚了一天

console.log(diffDays('2021-09-01', '2021-09-30'));
// 29

console.log(diffDays('2021-09-01', '2021-10-10'));
// 39

啥,不太懂你说的啥。
2021-09-01 2021-10-10 执行完方法后是40,不懂你说的31,30,是什么意思。
另外,为什么用split分割开"-"呢?
直接放进去就行啦,还不用判断是"-"还是"/"分割开

let oDate1 = new Date(beginTime)
let oDate2= new Date(endTime)
days = parseInt(Math.abs(oDate1- oDate2) / 1000 / 60 / 60 / 24);
推荐问题
宣传栏