js如何计算两个日期,差几个月零几天?

如果这样写的话,会出现负数24个月,-1天啊

function monthDayDiff(startDate,endDate){
     start = new Date(startDate);
    let end = new Date(endDate);
        end.setDate(end.getDate()+1);
    let year=end.getFullYear()-start.getFullYear();
    let month=end.getMonth()-start.getMonth();
    let day=end.getDate()-start.getDate();
    let data = new Array(12*year+month,day) ;
    return data;
}

console.log(monthDayDiff('2017-3-3','2019-3-1'));
阅读 12.4k
7 个回答
function monthDayDiff(startDate, endDate) {
    let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2];
    let start = new Date(startDate);
    let end = new Date(endDate);
    let year = end.getFullYear() - start.getFullYear();
    let month = end.getMonth() - start.getMonth();
    let day = end.getDate() - start.getDate();
    if (month < 0) {
        year--;
        month = end.getMonth() + (12 - start.getMonth());
    }
    if (day < 0) {
        month--;
        let index = flag.findIndex((temp) => {
            return temp === start.getMonth() + 1
        });
        let monthLength;
        if (index <= 6) {
            monthLength = 31;
        } else if (index > 6 && index <= 10) {
            monthLength = 30;
        } else {
            monthLength = 28;
        }
        day = end.getDate() + (monthLength - start.getDate());
    }
    console.log(`相差${12 * year + month}月${day}天`);
}
monthDayDiff('2017-3-3', '2019-3-1');

你这个问题不大严谨啊。
你说的月份是自然月还是以30天为一个月?
如果是自然月就是对应位置相减,用到Date.getFullYear(), Date.getMonth(), Date.getDate()
如果是以30天为一个月就是转换为时间戳然后自行计算,用到Date.getTime()

通过Date.parse()方法,把两个时间都转为时间戳(单位是毫秒),
在计算出两个时间戳之间的差,最后再写一个格式化时间的方法转一下

var d1 = '2017-01-01';
var d2 = '2017-03-03';

s1 = new Date(d1.replace(/\-/g, "/"));
s2 = new Date(d2.replace(/\-/g, "/"));

var time = s2.getTime() - s1.getTime();
var days = parseInt(time / (1000 * 60 * 60 * 24));

days即为相差天数

只能算天数,当然你一个月按30天计算的话,再除以30.

    var date = differencedate("2017-1-1","2017-3-3");
            console.log(date)
            function differencedate(start,end){
                var startdate = new Date(start);
                var enddate = new Date(end);
                return (enddate-startdate)/(24*60*60*1000);
            }

这是我曾经写过的小插件,可以参考一下

<script>
var startTime = "2017-04-04";
var calculationTime = function(startTime) {
    var s1 = new Date(startTime.replace(/-/g, "/")),
    s2 = new Date(),
    runTime = parseInt((s2.getTime() - s1.getTime()) / 1000);
    var year = Math.floor(runTime / 86400 / 365);
    runTime = runTime % (86400 * 365);
    var month = Math.floor(runTime / 86400 / 30);
    runTime = runTime % (86400 * 30);
    var day = Math.floor(runTime / 86400);
    runTime = runTime % 86400;
    var hour = Math.floor(runTime / 3600);
    runTime = runTime % 3600;
    var minute = Math.floor(runTime / 60);
    runTime = runTime % 60;
    var second = runTime;
    document.querySelector(".SiteRunningTime > .year").innerText = year;
    document.querySelector(".SiteRunningTime > .month").innerText = month;
    document.querySelector(".SiteRunningTime > .day").innerText = day;
    document.querySelector(".SiteRunningTime > .hour").innerText = hour;
    document.querySelector(".SiteRunningTime > .minute").innerText = minute;
    document.querySelector(".SiteRunningTime > .second").innerText = second
};
setInterval("calculationTime(startTime)", 1000);
</script>
<span class="SiteRunningTime">该站点运行了<label class="year">0</label>年<label class="month">0</label>月<label class="day">0</label>日<label class="hour">0</label>时<label class="minute">0</label>分<label class="second">0</label>秒</span>
var startStr = '2017-1-1';
var endStr = '2017-3-3';
var startAry ,endAry;
startAry = startStr.split('-');
endAry = endStr.split('-');
console.log(parseInt(endAry[0]) - parseInt(startAry[0]));
console.log(parseInt(endAry[1]) - parseInt(startAry[1]));
console.log(parseInt(endAry[2]) - parseInt(startAry[2]) + 1);

天数 + 1 ;ps:即加上2017-1-1这天。

let a=new Date('2017-3-3');
let b=new Date('2017-1-1');
let year=a.getFullYear()-b.getFullYear();
let month=a.getMonth()-b.getMonth();
let day=a.getDate()-b.getDate();
console.log(相差${year}年${month}月${day}天);

这个答案比我的写的更好点。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏