我已经尝试了堆栈溢出中的所有解决方案,但找不到确切的解决方案或问题答案。当我尝试使用getTime()转换日期时,有时会显示负值,有时是数字与手动计算的天数相比,答案中显示的天数似乎不正确。 我添加了用于计算的代码。请看看。
引荐:Difference between two dates in years, months, days in JavaScript
var date2 = new Date("2018-01-01");
var date1 = new Date("2017-01-01");
var diff = Math.floor(date2.getTime() - date1.getTime());
//1000*60*60*24
var secs = Math.floor(diff / 1000);
var mins = Math.floor(secs / 60);
var hours = Math.floor(mins / 60);
var days = Math.floor(hours / 24);
var months = Math.floor(days / 31);
var years = Math.floor(months / 12);
months = Math.floor(months % 12);
days = Math.floor(days % 31);
hours = Math.floor(hours % 24);
mins = Math.floor(mins % 60);
secs = Math.floor(secs % 60);
var message = "";
if (days <= 0) {
message += secs + " sec ";
message += mins + " min ";
message += hours + " hours ";
} else {
message += days + " days ";
if (months > 0 || years > 0) {
message += months + " months ";
}
if (years > 0) {
message += years + " years ago";
}
}
console.log(message);
//Expected result is : 1 year 0 months 0 days.
//Actual result is : 11 months 24 days.
答案 0 :(得分:-1)
一个月中没有31天。在非-年中,有30.417天。
答案 1 :(得分:-2)
尝试这样,但与您的预期结果不同。12 months
等于1 year
。
我的代码的结果是1 Year 0 Months 0 Days
。
var date2 = new Date("2021-01-01")
var date1 = new Date("2020-01-01");
function getdiff(date2, date1) {
var yeardate2 = date2.getYear();
var monthdate2 = date2.getMonth();
var datedate2 = date2.getDate();
var yeardate1 = date1.getYear();
var monthdate1 = date1.getMonth();
var datedate1 = date1.getDate();
var diff = {};
var res = "";
var yearString = "";
var monthString = "";
var dayString = "";
yearTot = yeardate2 - yeardate1;
if (monthdate2 >= monthdate1)
var monthTot = monthdate2 - monthdate1;
else {
yearTot--;
var monthTot = 12 + monthdate2 -monthdate1;
}
if (datedate2 >= datedate1)
var dateTot = datedate2 - datedate1;
else {
monthTot--;
var dateTot = 31 + datedate2 - datedate1;
if (monthTot < 0) {
monthTot = 11;
yearTot--;
}
}
diff = {
years: yearTot,
months: monthTot,
days: dateTot
};
if ( diff.years > 1 ) yearString = " years ";
else yearString = " year ";
if ( diff.months> 1 ) monthString = " months ";
else monthString = " month ";
if ( diff.days > 1 ) dayString = " days ";
else dayString = " day ";
res = diff.years + yearString + diff.months + monthString + diff.days + dayString;
return res;
}
console.log(getdiff(date2, date1))