一直试图解决这个问题一段时间没有成功,我在这里找到了几个类似的答案,但是这里的格式是重要的。我需要返回X年,X月,X天。2天之间的Javascript日期返回错误
你可以看看,我在这里做错了什么......天数不太对。
这里是一个bin
function inBetweenDays(y,m,d){
var user_date = new Date(y,m + 1,d);
var today_date = new Date();
var diff_date = (user_date - today_date);
var num_years = diff_date/31536000000;
var num_months = (diff_date % 31536000000)/2628000000;
var num_days = ((diff_date % 31536000000) % 2628000000)/86400000;
var years = Math.floor(Math.abs(num_years));
var months = Math.floor(Math.abs(num_months));
var days = Math.floor(Math.abs(num_days));
if (years >= 1) {
console.log(years + " years " + months + " months " + days + " days");
} else if (years <= 0 && months >= 0){
console.log(months + " months " + days + " days");
} else {
console.log(days + " days ");
}
}
inBetweenDays(2015,03,04);
inBetweenDays(2016,03,04);
inBetweenDays(2016,02,04);
inBetweenDays(2018,02,04);
不应该第三行是'new Date(y,m - 1,d)'而不是? – Nayuki
假设一天的时间长度为86400000毫秒,你就错了。请去研究为什么。 – CBroe
@Nayuki ...我认为它应该是m + 1,因为月份是以0为基础..... – Lucky500