Timestamp to word phrase in C#

Published on : Feb 6, 2011

Category : General

Saravana

Author

Ok, this is not rocket science topic, but when I looked for a sample I couldn’t find any decent one. With the popularity of facebook, twitter, stackoverflow etc its becoming more of a norm to represent the time stamp in words rather than simply date time value. sample word phrase sample time stamp This is what I come up with, people simply forget how powerful the .NET programming stack is. It didn’t take more than 15 minutes to come up with this helper.
 public static string DateDiffInWords(DateTime dateTimeBegin, DateTime dateTimeEnd)
        {
            TimeSpan diff = dateTimeBegin.Subtract(dateTimeEnd);

            if (diff.Days > 10)
            {
                string s = string.Format("{0} '{1} at {2}"
                    , dateTimeEnd.ToString("MMM dd")
                    , dateTimeEnd.ToString("yy")
                    , dateTimeEnd.ToString("HH:mm"));
                return  s;
            }
            if (diff.Days > 1)
                return string.Format("{0} days ago", Convert.ToInt32(diff.Days));
            if (diff.Days == 1)
                return "Yesterday";
            if (diff.Hours > 1)
                return string.Format("{0} hours ago", Convert.ToInt32(diff.Hours));
            if (diff.Minutes > 1)
                return string.Format("{0} minutes ago", Convert.ToInt32(diff.Minutes));
            if(diff.Seconds > 1)
                return string.Format("{0} seconds ago", Convert.ToInt32(diff.Seconds));

            //we should not reach here
            return string.Empty;
        }
Few sample calls:
Console.WriteLine(Date.DateDiffInWords(DateTime.Now, new DateTime(2011, 2, 5, 14, 45, 45)));
Console.WriteLine(Date.DateDiffInWords(DateTime.Now, new DateTime(2011, 1, 28, 14, 45, 45)));
Console.WriteLine(Date.DateDiffInWords(DateTime.Now, new DateTime(2011, 2, 5, 05, 45, 45)));
Console.WriteLine(Date.DateDiffInWords(DateTime.Now, new DateTime(2011, 2, 4, 14, 45, 45)));
Console.WriteLine(Date.DateDiffInWords(DateTime.Now, new DateTime(2011, 2, 3, 14, 45, 45)));
Console.WriteLine(Date.DateDiffInWords(DateTime.Now, new DateTime(2011, 2, 2, 14, 45, 45)));
Console.WriteLine(Date.DateDiffInWords(DateTime.Now, new DateTime(2011, 1, 2, 14, 45, 45)));
And the Outcome:
sample time stamps Nandri, Saravana