Converting dates or datetimes to "seconds/minutes/hours/days ago" using .NET

By Miguel Santos

This FAQ will provide code to convert dates or datetimes to "x seconds/minutes/hours/days ago" string. Basically the resulted string will represent the elapsed time.

Here is the source code in C#
        public string GetElapsedTimeAsString(DateTime givenDate)
             return ConvertTimeSpanToTotalAgo(DateTime.Now.Subtract(givenDate));

        private static string ConvertTimeSpanToTotalAgo(TimeSpan diffDate)
           StringBuilder d = new StringBuilder();
            if (diffDate.Days > 0)
                 d.AppendFormat("{0} Days ago, ", diffDate.Days);
            else if (diffDate.Minutes > 0)
                 d.AppendFormat("{0} Minutes ago, ", diffDate.Minutes);
            else if (diffDate.Seconds > 0)
                 d.AppendFormat("{0} Seconds ago, ", diffDate.Seconds);
            else if (diffDate.Milliseconds > 0)
                 d.AppendFormat("{0} Milliseconds ago", diffDate.Milliseconds);
            return d.ToString();

Even though the sample code is in C#, it can translated to VB.NET very easily, for example the sample usage code is:
Private Function GetElapsedTimeAsString(Dim givenDate As String) As String
   Return ConvertTimeSpanToTotalAgo(DateTime.Now.Subtract(givenDate))
End Function

Converting dates or datetimes to "seconds/minutes/hours/days ago" using .NET  (2222 Views)