Fork Of

Revisions

gist: 58985 Download_button fork
public
Public Clone URL: git://gist.github.com/58985.git
Embed All Files: show embed
JavaScript #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 
To make this trick work, I embed the time stamp for a given entry in the DOM as a custom attribute that I can query for conversion like this:
 
<li>
<span time="Feb 05, 2009 15:30:00 GMT">09:30 AM CST (15:30 GMT)</span> /
The aliens came out of no where and took Basecamp!
We're trying to hunt them down now. Stay tuned while we bring the lasers online.
</li>
 
I only want to convert the entries from today into relative time. The entries from yesterday and before should just use the specific time-only style. This means looking for just the span’s inside li’s from the ul with the class “today”. They’re then converted when the document is loaded with this function:
 
convert_all_times_from_today_to_words: function() {
$$('.today li span').each(function(e) {
e.innerHTML = this.time_ago_in_words_with_parsing(e.getAttribute('time'));
}, this);
}
 
The function uses a simple DateHelper JavaScript class that mimicks the DateHelper in Rails.
 
*/
 
 
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);
  },
  
  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 = (distance_in_seconds / 60).floor();
 
    if (distance_in_minutes == 0) { return 'less than a minute ago'; }
    if (distance_in_minutes == 1) { return 'a minute ago'; }
    if (distance_in_minutes < 45) { return distance_in_minutes + ' minutes ago'; }
    if (distance_in_minutes < 90) { return 'about 1 hour ago'; }
    if (distance_in_minutes < 1440) { return 'about ' + (distance_in_minutes / 60).floor() + ' hours ago'; }
    if (distance_in_minutes < 2880) { return '1 day ago'; }
    if (distance_in_minutes < 43200) { return (distance_in_minutes / 1440).floor() + ' days ago'; }
    if (distance_in_minutes < 86400) { return 'about 1 month ago'; }
    if (distance_in_minutes < 525960) { return (distance_in_minutes / 43200).floor() + ' months ago'; }
    if (distance_in_minutes < 1051199) { return 'about 1 year ago'; }
 
    return 'over ' + (distance_in_minutes / 525960).floor() + ' years ago';
  }
};