【发布时间】:2016-02-05 01:45:12
【问题描述】:
一直试图解决这个问题,但没有成功,我在这里找到了几个类似的答案,但格式在这里很重要。我需要返回 X 年 X 月 X 天。
你能不能看看,我这里做错了什么……天数不太对。
这是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)吗? -
假设一天是
86400000毫秒长,你已经错了。请去研究为什么。 -
@Nayuki...我认为应该是 m + 1,因为月份是从 0 开始的.....
-
您是否在寻找两个日期之间的 日历 差异?如果您希望 3 月 1 日为 2 个月,即 1 月 1 日之后的 0 天,无论闰年如何,都很难使用两个日期之间的毫秒来得出答案。
-
对于超过几个月的时间段,您的结果几乎肯定是错误的,因为天、月和年的长度各不相同。您确定这不是 Return Date in format ( x years, x months, x days) 的副本(它本身就是副本)吗?您可能应该将 today_date 的小时数归零。
标签: javascript date math