-
-
Save deadkarma/1989808 to your computer and use it in GitHub Desktop.
Calculate time_ago_in_words for javascript
This file contains 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 DateHelper = { | |
// Takes the format of "Jan 15, 2007 15:45:00 GMT" and converts it to a relative time | |
// Ruby strftime: %b %d, %Y %H:%M:%S GMT | |
time_ago_in_words_with_parsing: function(from) { | |
var date = new Date; | |
date.setTime(Date.parse(from)); | |
return this.time_ago_in_words(date); | |
}, | |
// Takes a timestamp and converts it to a relative time | |
// DateHelper.time_ago_in_words(1331079503000) | |
time_ago_in_words: function(from) { | |
return this.distance_of_time_in_words(new Date, from); | |
}, | |
distance_of_time_in_words: function(to, from) { | |
var distance_in_seconds = ((to - from) / 1000); | |
var distance_in_minutes = Math.floor(distance_in_seconds / 60); | |
var tense = distance_in_seconds < 0 ? " from now" : " ago"; | |
distance_in_minutes = Math.abs(distance_in_minutes); | |
if (distance_in_minutes == 0) { return 'less than a minute'+tense; } | |
if (distance_in_minutes == 1) { return 'a minute'+tense; } | |
if (distance_in_minutes < 45) { return distance_in_minutes + ' minutes'+tense; } | |
if (distance_in_minutes < 90) { return 'about an hour'+tense; } | |
if (distance_in_minutes < 1440) { return 'about ' + Math.floor(distance_in_minutes / 60) + ' hours'+tense; } | |
if (distance_in_minutes < 2880) { return 'a day'+tense; } | |
if (distance_in_minutes < 43200) { return Math.floor(distance_in_minutes / 1440) + ' days'+tense; } | |
if (distance_in_minutes < 86400) { return 'about a month'+tense; } | |
if (distance_in_minutes < 525960) { return Math.floor(distance_in_minutes / 43200) + ' months'+tense; } | |
if (distance_in_minutes < 1051199) { return 'about a year'+tense; } | |
return 'over ' + Math.floor(distance_in_minutes / 525960) + ' years'; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment