4

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!

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Paul
  • 12,392
  • 4
  • 48
  • 58
  • 2
    possible duplicate of [How do I calculate relative time?](http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time) – cHao Sep 05 '10 at 01:05
  • Your question is tagged C#, but as you mention Facebook, which updates the "time ago" value without refreshes, you would also (or only?) need a JavaScript implementation. – devio Sep 05 '10 at 01:06
  • cHao is right, there's even an answer from Jeff http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/12#12 – devio Sep 05 '10 at 01:08
  • Thanks guys, I searched but did not see that result. Thanks! – Paul Sep 05 '10 at 01:49

2 Answers2

7

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
  • 300,895
  • 165
  • 679
  • 742
  • I don't think timeago works with different languages, just english. –  Sep 05 '10 at 01:45
  • 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 Sep 05 '10 at 02:49
  • @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 Sep 05 '10 at 03:35
  • 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 Sep 05 '10 at 14:49
2

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 Widman
  • 6,329
  • 4
  • 23
  • 32