Skip to content

Instantly share code, notes, and snippets.

@netojoaobatista
Created April 26, 2012 20:09
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save netojoaobatista/2502709 to your computer and use it in GitHub Desktop.
Save netojoaobatista/2502709 to your computer and use it in GitHub Desktop.
Returns the difference between two Date objects.
Object.defineProperty(Date.prototype,"diff",{
writable: false, configurable: false, enumerable: true,
/**
* Returns the difference between two Date objects.
* @param {Date} The date to compare to.
* @return {Object}
* @throws {TypeError}
*/
value: function(date) {
if (date instanceof Date){
var ms = this-date;
var diff = {};
for ( diff.years = 0; ms>=31536000000; diff.years++, ms -= 31536000000);
for ( diff.months = 0; ms>=2628000000; diff.months++, ms -= 2628000000);
for ( diff.days = 0; ms>=86400000; diff.days++, ms -= 86400000);
for ( diff.hours = 0; ms>=3600000; diff.hours++, ms -= 3600000);
for ( diff.minutes = 0; ms>=60000; diff.minutes++, ms -= 60000);
for ( diff.seconds = 0; ms>=1000; diff.seconds++, ms -= 1000);
diff.milliseconds = ms;
return diff;
}
throw new TypeError("invalid date");
}
});
var date = new Date("2012-04-26T17:05:14.000Z");
var diff = date.diff(new Date("2012-04-24T21:29:42.000Z"))
console.log(JSON.stringify(diff)); //{"years":0,"months":0,"days":1,"hours":19,"minutes":35,"seconds":32,"milliseconds":0}
@suissa
Copy link

suissa commented Apr 26, 2012

mtoooo sagaz, parabens.

@leobetosouza
Copy link

Isso teria sido muito útil num projeto que eu tava trabalhando à uns 2 anos... devidamente guardado para usos futuros =)

@suissa
Copy link

suissa commented Apr 27, 2012

Eh muito bom para usar naqueles esquemas de comentarios e murais a la facebook.

@millermedeiros
Copy link

Tenho algo parecido no amd-utils: time/parseMs - é só passar a diferença em milliseconds e ele transforma o valor em um objeto tipo o seu.

Ao invés de usar múltiplos loops vc pode usar minutes = Math.floor( ms / 60000 ) % 60 - veja a implementação do parseMs e math/countSteps.

Eu sempre evito adicionar métodos novos em objetos que eu não criei... Evita conflitos com código de terceiros e código fica mais portátil.

@suissa
Copy link

suissa commented May 4, 2012

BOA!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment