views:

272

answers:

3

You may have noticed that certain web applications (for example, certain parts of GMail) display dates in a more human-readable format than simply DD/MM/YYYY.

For example, if I open up a mail item from the 23rd (which happens to be 3 days ago at the time of writing, I'll get the following:

Dec 23 (3 days ago)

I'd like to implement similar logic to this in my own web application.

For example, when dealing with a .NET TimeSpan object, I'd like to convert it to text such as the following:

2 months

3 days

Is there a .NET library capable of doing this already?

If not I might build something basic and open-source it.


I've made a basic start here:

public static class TimeSpanHelpers
{
    public static string ToHumanReadableString(
        this TimeSpan timeSpan)
    {
        if (timeSpan.TotalDays > 30)
            return (timeSpan.TotalDays / 30) + " month(s)";

        if (timeSpan.TotalDays > 7)
            return (timeSpan.TotalDays / 7) + " week(s)";

        return (timeSpan.TotalDays) + " day(s)";
    }
}
+3  A: 

The Noda Time group is in the process of doing just this. Come on over and join the fun. Forgot to mention the project location Nota Time project

James Keesey
Cool stuff! I'll head over there.
jonathanconway
+1  A: 

I've got a simple algorithm for that on my blog that you could extend: http://www.robfe.com/2009/09/timeago-for-csharp/

Not very different to yours I'm afraid...

Rob Fonseca-Ensor
+1  A: 

See also this question: http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time There you'll find several C# implementations for relative time (i.e. "5 mins ago", "10 days ago").

Juha Syrjälä