Skip to content

Formatting date time to a relative / "x moments ago" format in .NET

After looking on the net and not being completely satisified with the solutions out there on formatting to this style, I headed over to trusty stackoverflow.com and did really like the one Jeff Atwood and the team use on stackoverflow.com, until I saw the more concise version down below.
Mind you this is the one I initially tried, and teared my hair out as when doing some AddMinutes(-40) tests it was returning things like ’40 hours ago’.

However Michael Wolfenden pointed out an excellent routine using Lambda syntax as well, very elegant.  (I wrapped it into a handy ASP.NET Html Helper Extension for convenience).

        ///
        /// Format date/time object into html representation of 'relative time' format, eg. "5 seconds ago".
        ///
        ///
        ///
        ///
        public static string FormatDateTimeRelative(this HtmlHelper htmlHelper, DateTime? value)
        {
            if (value.HasValue)
            {
                // As suggested on stackoverflow.com and found to be the most comprehensive method.
                // Jeff Atwood's method is nice, but this is more concise.
                // http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time

                TimeSpan oSpan = DateTime.Now.Subtract(value.Value);
                double TotalMinutes = oSpan.TotalMinutes;
                string Suffix = " ago";

                if (TotalMinutes < 0.0)
                {
                    TotalMinutes = Math.Abs(TotalMinutes);
                    Suffix = " from now";
                }

                Dictionary aValue = new Dictionary();
                aValue.Add(0.75, () => "less than a minute");
                aValue.Add(1.5, () => "about a minute");
                aValue.Add(45, () => string.Format("{0} minutes", Math.Round(TotalMinutes)));
                aValue.Add(90, () => "about an hour");
                aValue.Add(1440, () => string.Format("about {0} hours", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24
                aValue.Add(2880, () => "a day"); // 60 * 48
                aValue.Add(43200, () => string.Format("{0} days", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30
                aValue.Add(86400, () => "about a month"); // 60 * 24 * 60
                aValue.Add(525600, () => string.Format("{0} months", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365
                aValue.Add(1051200, () => "about a year"); // 60 * 24 * 365 * 2
                aValue.Add(double.MaxValue, () => string.Format("{0} years", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));

                return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix;
            }
            return string.Empty;
        }

Here is the original post on http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time

But if you are looking for something a little more dynamic and wish to have DOM updates on the fly while preserving your original timestamp in yyyy:MM:dd HH:mm:ss on the page or whatever, check the jquery.timeago plugin also suggested on that post.

Very cool.

VN:F [1.9.1_1087]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.1_1087]
Rating: 0 (from 0 votes)
Bookmark and Share
kick it on DotNetKicks.com
Shout it

NOW, FOR A WORD FROM OUR SPONSORS

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*
My name is Graham O'Neale and I'm a software architect from Gold Coast, Australia. I am an overtime thinker, full time coder and awake part time in the real world. I have a keen interest in software development, particularly in the realm of programming (C#, ASP.NET, ASP.NET MVC, LINQ (2 SQL), Entity Framework, Silverlight, Blend, WCF, WPF) and a keen interest in the cutting edge and innovation. I have a new found love for design patterns, ALT.NET practices and well crafted software architecture. The purpose of this blog is to express any thoughts, findings, tips and gripes along my travels in the wonderful world of coding and technology...