JavaScript year,month,day,hour,minute,second difference

假如想象 提交于 2021-02-08 09:10:35

问题


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"
}

Thanks for the help


回答1:


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

EDIT: 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)?

EDIT2: corrected my truely appalling maths.

EDIT3: 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');

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




回答2:


Use moment.js which is a really good function and you can have time returned in plain text form.

http://momentjs.com/

Read the API documentation and with some clever hacking on the function, you can get the required output string format. And btw there is no specific library that can output dates in your required format I am aware of. So, let me know if you get somewhere and need help with moment.js




回答3:


You can just subtract two dates to get the milliseconds, and then work from there:

var date1 = new Date("2012/06/12 12:00:30");
var date2 = new Date("2013/06/15 12:00:40");
var diff = Math.abs(date2 - date1);
var years = Math.floor(diff/(1000*60*60*24*365)); // 1
var months = Math.floor((diff - years) / (1000*60*60*24*30)) % 12; // 0
(...)


来源:https://stackoverflow.com/questions/16597509/javascript-year-month-day-hour-minute-second-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!