Created
April 26, 2012 20:09
-
-
Save netojoaobatista/2502709 to your computer and use it in GitHub Desktop.
Returns the 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
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"); | |
} | |
}); |
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 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} |
Isso teria sido muito útil num projeto que eu tava trabalhando à uns 2 anos... devidamente guardado para usos futuros =)
Eh muito bom para usar naqueles esquemas de comentarios e murais a la facebook.
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.
BOA!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mtoooo sagaz, parabens.