简体   繁体   中英

Find the difference between two dates

How can i find the difference between two dates in this format Year, Month (Must be < 12 if > 12 the Year++), Days ( Must be < 30 if > 30 then month++), Hours (must be < 24 if > 24 then day++)

i wont have a format like this

year 3, month 34 (i will calc this 34 in years), dasy 345 ( an this value too)

i have this code

http://jsfiddle.net/AQSWu/

var currentTo  = new Date(2015, 6, 1),
    currentFrom  = new Date(2013,11,1), 
    year         = currentTo.getFullYear() - currentFrom.getFullYear(),
                m1  = currentTo.getMonth() + 1,
                m2  = currentFrom.getMonth() + 1,
                month   = m1 <= m2 ? (12 - m2) + m1 : m1 - m2;

alert("From: " + currentFrom);
alert("To :" + currentTo);


            if (currentTo.getDate() < currentFrom.getDate()) {
                month = month - 1;
            }

            if (month >= 12){ month = 0; }

alert(year + ' ' + month);

but i have no idea how i can calc days an hours

Don't substract year, month, day etc separately, but just get the difference between the dates (in milliseconds) and then output that in a format (or unit) that you want:

var currentTo  = new Date(2015, 6, 1),
    currentFrom  = new Date(2013,11,1),
    difference = currentTo - currentFrom; // number conversion is implicit
var hours = difference / 3600000; // ms -> h
    // now do your maths

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM