我一直在尝试应对这一挑战。它最终使用过去的日期,它给了我想要的格式(年,月,日),但不适用于将来的日期。我如何重做这个例子,所以它也适用于未来的日期?截至目前,我得到一个空字符串。
*
答案 0 :(得分:2)
您只需使用Math.abs()
获取yearsDiff
function reworkedInBetweenDays(year, month, day) {
var today = new Date();
var fromdate = new Date(year, month - 1, day);
var yearsDiff = Math.abs(today.getFullYear() - fromdate.getFullYear()); //HERE
var monthsDiff = today.getMonth() - fromdate.getMonth();
var daysDiff = today.getDate() - fromdate.getDate();
if (monthsDiff < 0 || (monthsDiff === 0 && daysDiff < 0))
yearsDiff--;
if (monthsDiff < 0)
monthsDiff += 12;
if (daysDiff < 0) {
var fromDateAux = fromdate.getDate();
fromdate.setMonth(fromdate.getMonth() + 1, 0);
daysDiff = fromdate.getDate() - fromDateAux + today.getDate();
monthsDiff--;
}
var result = [];
if (yearsDiff > 0)
result.push(yearsDiff + (yearsDiff > 1 ? " years" : " year"));
if (monthsDiff > 0)
result.push(monthsDiff + (monthsDiff > 1 ? " months" : " month"));
if (daysDiff > 0)
result.push(daysDiff + (daysDiff > 1 ? " days" : " day"));
return result.join(', ');
}
console.log(reworkedInBetweenDays(2013, 4, 8));
console.log(reworkedInBetweenDays(2014, 1, 16));
console.log(reworkedInBetweenDays(2016, 1, 31));
console.log(reworkedInBetweenDays(2017, 2, 16));
答案 1 :(得分:1)
它可以在最后添加此代码
if (yearsDiff < 0)
result.push(yearsDiff*(-1) + (yearsDiff*(-1) > 1 ? " years in the future" : " year in the future"));
if (monthsDiff < 0)
result.push(monthsDiff*(-1) + (monthsDiff*(-1) > 1 ? " months in the future" : " month in the future"));
if (daysDiff < 0)
result.push(daysDiff*(-1) + (daysDiff*(-1) > 1 ? " days in the future" : " day in the future"));
答案 2 :(得分:0)
monthsDiff
和daysDiff
都为零且yearsDiff
为-1,这意味着它们都没有在底部设置if语句。当所有这些值为零或负值时,您需要添加一些代码来处理。