我想计算两个日期之间的确切月份和日期。
如果我的开始日期是" 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);
答案 0 :(得分:2)
试试这个:
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;
}
答案 1 :(得分:1)
也许我解释错了但不应该只是
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');
问候克里斯