开发者

Display time padded how Stackoverflow and Facebook do - C#

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 acco开发者_开发技巧mplish this that would be great!


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


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜