Created
March 11, 2010 06:03
-
-
Save JonCrawford/328890 to your computer and use it in GitHub Desktop.
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
| // ============================================================================================ | |
| // = Cachable Time Ago In Words - http://nullstyle.com/wp-content/uploads/2007/11/jsdates.txt = | |
| // ============================================================================================ | |
| var DateHelper = { | |
| timeAgoInWords: function(from) { | |
| return this.distanceOfTimeInWords(new Date().getTime(), from); | |
| }, | |
| distanceOfTimeInWords: function(to, from) { | |
| seconds_ago = ((to - from) / 1000); | |
| minutes_ago = Math.floor(seconds_ago / 60); | |
| if(minutes_ago == 0) { return "less than a minute"; } | |
| if(minutes_ago == 1) { return "a minute"; } | |
| if(minutes_ago < 45) { return minutes_ago + " minutes"; } | |
| if(minutes_ago < 90) { return " about 1 hour"; } | |
| hours_ago = Math.round(minutes_ago / 60); | |
| if(minutes_ago < 1440) { return "about " + hours_ago + " hours"; } | |
| if(minutes_ago < 2880) { return "1 day"; } | |
| days_ago = Math.round(minutes_ago / 1440); | |
| if(minutes_ago < 43200) { return days_ago + " days"; } | |
| if(minutes_ago < 86400) { return "about 1 month"; } | |
| months_ago = Math.round(minutes_ago / 43200); | |
| if(minutes_ago < 525960) { return months_ago + " months"; } | |
| if(minutes_ago < 1051920) { return "about 1 year"; } | |
| years_ago = Math.round(minutes_ago / 525960); | |
| return "over " + years_ago + " years"; | |
| } | |
| } |
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
| # usage: <span class="time"><%= cachable_time_ago_in_words(o.created_at) %> ago</span> | |
| def cachable_time_ago_in_words(from, id_prefix = 'time_ago') | |
| id = "#{id_prefix}_#{from.to_i}" | |
| content_tag(:span, from.to_datetime.to_formatted_s(:long), :id => id) << | |
| javascript_tag("$('#{id}').update(DateHelper.timeAgoInWords(#{(from.to_i * 1000).to_json}))") | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment