Get time intervals between two Dates

Submitted by:Andery Smith

Date added:20 June, 2013

Category:JavaScript

JavaScript code to get time intervals between two Dates

Tags: time interval

Code Snippet:

    /* Get time intervals between two Dates v2.0
*
* This work is licensed under a Creative Commons Attribution 3.0 Unported License
* http://creativecommons.org/licenses/by/3.0/
*
* Author: Andy Harrison, http://dragonzreef.com/
* Date: 16 September 2011
*/

Date.isLeapYear = function(year){ return (year%400 == 0 || (year%4 == 0 && year%100 != 0)); }
Date.prototype.isLeapYear = function(){ return Date.isLeapYear(this.getFullYear()); }

//get the number of days in a given month of a given year (month being 0-11)
Date.daysInMonth = function(year, month){ return ([31, (Date.isLeapYear(year)?29:28), 31,30,31,30,31,31,30,31,30,31])[month]; }
Date.prototype.daysInMonth = function(){ return Date.daysInMonth(this.getFullYear(), this.getMonth()); }

//returns an object with time intervals between two Dates
//Date objects, milliseconds, or date strings are accepted arguments
//object properties: years, months, weeks, days, hours, minutes, seconds, milliseconds
//each part is *in addition* to the sum of the larger parts; e.g., if there are 17 days between the two dates, .weeks==2 and .days==3
Date.timeBetween = function(dateA, dateB)
{
dateA = new Date(dateA);
dateB = new Date(dateB);
if(isNaN(dateA.valueOf()+dateB.valueOf())) return null; //invalid date(s)

if(dateA.valueOf() > dateB.valueOf())
{
var tmp = dateA;
dateA = dateB;
dateB = tmp;
}

var parts = {};

//years
parts.years = dateB.getFullYear() - dateA.getFullYear();

//months
dateA.setFullYear(dateB.getFullYear());
parts.months = dateB.getMonth() - dateA.getMonth();

//days
dateA.setMonth(dateB.getMonth());
if(dateA.valueOf() > dateB.valueOf())
{
dateA.setMonth(dateA.getMonth()-1);
parts.months--;
}
parts.days = Math.floor((dateB.valueOf()-dateA.valueOf())/86400000);

//time
parts.hours = dateB.getHours() - dateA.getHours();
parts.minutes = dateB.getMinutes() - dateA.getMinutes();
parts.seconds = dateB.getSeconds() - dateA.getSeconds();
parts.milliseconds = dateB.getMilliseconds() - dateA.getMilliseconds();

//weeks
parts.weeks = Math.floor(parts.days/7);
parts.days = parts.days%7;

//adjust for negative values
if(parts.milliseconds < 0){ parts.milliseconds = 1000+parts.milliseconds; parts.seconds--; }
if(parts.seconds < 0){ parts.seconds = 60+parts.seconds; parts.minutes--; }
if(parts.minutes < 0){ parts.minutes = 60+parts.minutes; parts.hours--; }
if(parts.hours < 0) parts.hours = 24+parts.hours;
if(parts.months < 0){ parts.months = 12+parts.months; parts.years--; }

return parts;
}
 
 

Comments