lost password?

home
•  xaraya
•  rails +
•  django
•  webdev
•  xamp
•  musings

rss
Tag this page
   

ยป Blogs that link here
last modified: Jul 31, 2007
(first posted: Jul 30, 2007)
(1738 Reads)
keywords: date helper time
Permalink

My timestamp holy grail

In response to "The Perfect Timestamp" ... here's what I really want (and did).

One problem in calculating "1 day ago" is it's based on hours, not date. I think of days as calendar dates rather than strict 24 hours ago.

Another problem is while I like the narrative way of describing "ago", I still want to show the actual time, thus "about 3 hours ago at 4:31PM" suits me.

As we go further back in time, the amount of detail changes. Any date this year, don't need the year. Within the past week, say something like "Last Tuesday"

My algorithm:

If not the same year, show "dd-mmm-yyyy hh:mm" (full date and time, no day of week)

If today,

if <4 minutes, show "About xx minutes ago"

else if <4 hours ago, show "About xx [hours|minutes] ago at hh:mm"

else "Today at hh:mm"

if yesterday, show "Yesterday at hh:mm"

if 2 to 6 days ago, "Last [dayofweek], dd-mmm at hh:mm"

else "[dayofweek], dd-mmm hh:mm" (no year)

Here's some example output:

"less than a minute ago"

"about 42 minutes ago at 7:31PM"

"Today at 1:20PM"

"Yesterday at 7:31PM"

"Last Wed, 18-Jul at 7:31PM"

"Sat, 28-Jun at 7:31PM"

"28-Jul-2006 at 7:31PM"

Here's the helper code (btw, I left the timezone stuff in for spice)

 

  def smart_time_ago( was, is = TzTime.now )
    was = tz_convert( was )
    was = was.to_time if was.respond_to?(:to_time)
    is = tz_convert( is )
    if (was.year != is.year) # not this year
                    time = was.strftime("%d-%b-%Y %l:%M%p")
    else 
      case (is.yday - was.yday)
        when 0 # today           
          if (is - was < 4.minutes)
                    time = distance_of_time_in_words(was,is) + " ago" 
          elsif (is - was < 4.hours)
                    time = distance_of_time_in_words(was,is) + was.strftime(" ago at %l:%M%p")     
          else
                    time = was.strftime("Today at %l:%M%p")
          end
        when 1 # yesterday
                    time = was.strftime("Yesterday at %l:%M%p")
        when 2..6 # past week 
                    time = was.strftime("Last %a, %d-%b at %l:%M%p")
        else # this year
                    time = was.strftime("%a, %d-%b at %l:%M%p")
      end
    end
    return time.squeeze(' ')
  end

 

 

There are no comments attached to this item.

Post a new comment

How many days in a week?

Name :