Last active
July 20, 2016 12:32
-
-
Save sergiks/6f201d64568363a9c1906abbced17b3a to your computer and use it in GitHub Desktop.
Difference between two Date objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var diff | |
,I = new Date('2016-01-01T00:00:02') | |
,O = new Date('2017-01-01T00:00:01') | |
; | |
/** | |
* Calendar difference between two dates | |
* | |
* It takes into account the number of days in a month, | |
* leap years, seconds and timezones. | |
* | |
* @author Sergei Sokolov | |
* Moscow, July 19, 2016 | |
*/ | |
diff = { | |
years : 0 | |
,months : 0 | |
,days : 0 | |
,hours : 0 | |
,minutes: 0 | |
,seconds: 0 | |
}; | |
diff.seconds += O.getSeconds() - I.getSeconds(); | |
if( diff.seconds < 0) { | |
diff.seconds += 60; | |
diff.minutes--; | |
} | |
diff.minutes += O.getMinutes() - I.getMinutes(); | |
if( diff.minutes < 0) { | |
diff.minutes += 60; | |
diff.hours--; | |
} | |
diff.hours += O.getHours() - I.getHours(); | |
if( diff.hours < 0) { | |
diff.hours += 24; | |
diff.days--; | |
} | |
diff.days += O.getDate() - I.getDate(); | |
if( diff.days < 0) { | |
diff.days += new Date( O.getFullYear(), O.getMonth(), 0).getDate(); | |
diff.months--; | |
} | |
diff.months += O.getMonth() - I.getMonth(); | |
if( diff.months < 0) { | |
diff.months += 12; | |
diff.years--; | |
} | |
diff.years += O.getFullYear() - I.getFullYear(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment