繁体   English   中英

如何计算两个日期之间的时间段-angularjs

[英]How to calculate time period between two dates - angularjs

我想计算两个日期之间的确切月份和天数。

如果我的开始日期是“ 2014年1月12日”,而我的结束日期是“ 2017年3月27日”。

我应该得到“ 38个月零15天”。

但是我只能找到没有。 开始日期和结束日期之间的天数。 我需要一些帮助来查找开始日期和结束日期之间的月份和日期。

然后,我需要将15天除以否。 结束日期月份的天数。

谁能帮我? 我是最新的功能。

var date = new Date();
            console.log("date: "+date);
            var currentDate = $filter('date')(date, "yyyy-MM-dd HH:mm:ss");

            $scope.userdob = "2017-01-29";
            var dobdate = $filter('date')($scope.userdob, "yyyy-MM-dd HH:mm:ss");

            console.log("dob: "+dobdate);

            /* differentiate Date */            
            var date1 = $filter('date')($scope.userdob, "yyyy-MM-dd");
            var date2 = $filter('date')(date, "yyyy-MM-dd");

            date1 = date1.split('-');
            date2 = date2.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
var date1_unixtime = parseInt(date1.getTime() / 1000);
var date2_unixtime = parseInt(date2.getTime() / 1000);

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;

// and finaly, in days :)
$scope.timeDifferenceInDays = timeDifferenceInHours  / 24;
            console.log("timeDifferenceInDays: "+$scope.timeDifferenceInDays);

尝试这个:

 function monthCalculator() { var d1 = new Date(); var d2 = new Date('2013', '02', 12); var years = d1.getFullYear() - d2.getFullYear(); var months = d1.getMonth() - d2.getMonth(); var totalMonths = (years * 12) + months; var d1Date = d1.getDate(); var d2Date = d2.getDate(); var days = d1Date - d2Date; var d1LastDate = null; var d2LastDate = null; if(days < 0) { var d1LastDate = new Date(d1.getFullYear(), d1.getMonth() + 1, 0).getDate(); var d2LastDate = new Date(d2.getFullYear(), d2.getMonth() + 1, 0).getDate(); if(d1Date != d1LastDate || d2Date != d2LastDate) { totalMonths -= 1; days = (new Date(d2.getFullYear(), d2.getMonth() + 1, 0).getDate()) + days; } else { days = 0; } } console.log(totalMonths); return totalMonths; } 

也许我解释错了,但不应该只是

var diffMonths = date2.getMonth() - date1.getMonth();
var diffDays = date2.getDate() - date1.getDate();
var diffYears = date2.getYear() - date1.getYear();
    diffMonths += 12* diffYears

if(diffDays<0){
       diffMonths -= 1;
       var daysInMonth = new Date(date2.getYear(), date2.getMonth()-1, 0).getDate();
       diffDays = daysInMonth + diffDays;
}
console.log('The difference between the two dates is ' + diffMonths + ' months and ' + diffDays + ' days');

克里斯问候

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM