JavaScript年,月,日,小时,分钟,秒差

JavaScript年,月,日,小时,分钟,秒差

问题描述:

我正在尝试寻找答案,但找不到任何答案.我正在尝试创建一个JavaScript函数,该函数需要两个日期并以"x年,y月,z天,小时,b分钟,c秒"的格式返回字符串.通常的迭代除法失败,因为几个月可以有不同的天数.我发现了几个来源,但是它们最多可以省去几天/几小时/几分钟,而忽略了几个月的问题,或者它们只是错误地平均了一个月的天数.

I was trying to search for the answer, but I couldn't find any. I'm trying to create a JavaScript function, that takes two dates and returns a string in the format of "x years, y months, z days, a hours, b minutes, c seconds". The usual iterated division fails, because months can have different number of days. I found several sources, but they either go only up to days/hours/minutes omitting the months problem, or they just erroneously average days in month.

function dateDifference(date) {
    now = new Date();
    ??;
    return difference; //returns something like "x years, y months, z days, a hours, b minutes, c seconds"
}

感谢您的帮助

使用.getTime将日期转换为毫秒:

Use .getTime to convert the dates into milliseconds:

var date1 = new Date(),
    date2 = new Date(someDate),
    diff = Math.abs(date1.getTime() - date2.getTime());

// then convert into years, months, etc

您无法摆脱平均几个月的时间,因为问题通常是模棱两可的.例如,如果计算2月3日与3月10日之间的差是1个月7天(假设2月是28天)还是1个月4天(假设3月是31天)?

You can't get away from averaging the length of months as the problem will often be ambiguous. e.g if calculating the difference between 3rd Feb and 10th Mar is that 1 month and 7 days (assuming a month is 28 days as in Feb) or 1 month and 4 days (assuming a month is 31 days as in March)?

更正了我真正令人震惊的数学.

corrected my truely appalling maths.

实际上,考虑到这一点,任何正常的人都将第一个月到最后一个月的一天换位,然后用它来计算天差.所以:

Actually, thinking about it, any normal human being transposes the day from the first month into the last month and uses that to calculate the difference in days. So:

var date1 = new Date(),
    date2 = new Date(1981, 10, 18);
    switch = (date2.getTime() - date1.getTime()) < 0 ? false : true, // work out which is the later date
    laterDate = switch ? date2 : date1;
    earlierDate = switch ? date1 : date2;
    dayDiff = laterDate.getDate() - earlierDate.getDate(),
    monthDiff = laterDate.getMonth() - earlierDate.getMonth(), // javascript uses zero-indexed months (0-11 rather than the more conventional 1-12)
    yearDiff = laterDate.getFullYear() - earlierDate.getFullYear(),
    months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 

if (dayDiff < 0) {
    monthDiff--;
    dayDiff += months[laterDate.getMonth()-1]; // -1 because we want the previous month
}

if (monthDiff < 0) {
    yearDiff--;
    monthDiff += 12;
}

console.log(yearDiff+' years, '+monthDiff+' months, '+dayDiff+' days');

我认为这可以带给我们大部分帮助,但我们仍然必须考虑leap年

I think this gets us most of the way there but we still have to consider leap years

纠正了一些错误(有时但不幸的是,并非总是取消)

EDIT 4: Corrected a couple of (sometimes but, unfortunately, not always cancelling out) off by 1 errors