views:

89

answers:

2

I have a ASP.NET MVC 2 app I am building and users are allowed to post data in certain sections. I would like to display the "Posted At" in the same format that Stackoverflow and Facebook do.

i.e. On this site when I post this question it will display "asked 3 seconds ago" then "asked 3 mins ago" and after a few day it will display the date.

My app is C#, if anyone can point me in the right direction on the best way to accomplish this that would be great!

+6  A: 

Have a look at the jQuery plugin, timeago. I'm using it on a site that I'm building and it works great.

Drew Noakes
I don't think timeago works with different languages, just english.
Vince
How does this work with Utc time?
Paul
Yes I think you're right -- just English. Still, it should be a simple enough script so you can customise it as needed.
Drew Noakes
@Paul, my understanding is that it works only with local times. Still, standard practice is to convert from UTC to local on the machine in said time zone. So, convert to local on the client's PC, then use timeago to deal with it. I wouldn't be surprised if _timeago_ understood properly annotated UTC times (there's an ISO suffix for this but it's too late and I'm too inebriated to recall it...)
Drew Noakes
timeago also has the nice feature that the actual time is available as a tooltip, in case you need something more precise than 'one month ago'.
Drew Noakes
+2  A: 

In C# it looks basically like this. The other answer is javascript, but that doesn't seem to be your question.

            DateTime now = DateTime.UtcNow;
            DateTime postedAt = new DateTime();
            var age = now.Subtract(postedAt);
            if (age < new TimeSpan(0, 1, 0))
                return (((int)age.TotalSeconds).ToString() + " seconds ago");
            else if (age < new TimeSpan(1, 0, 0))
                return (((int)age.TotalMinutes).ToString() + " minutes ago");
            else if (age < new TimeSpan(24, 0, 0))
                return (((int)age.TotalHours).ToString() + " hours ago");
            else
                return (((int)age.TotalDays).ToString() + " days ago");
jarrett