3

Whats the best way to get a datetime from sql server and convert it to use friendly strings like so:

if its more than 1 day > 1 Day ago.
more than 7 days > 1 weeks ago
1 year ago
3 minutes ago
56 seconds ago.

etc. Can this be done easily?

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
sprocket12
  • 5,368
  • 18
  • 64
  • 133

1 Answers1

6

Your best bet is to make a DateTime extension method:

public static class DateTimeExtensions
{
    public static string ToRelative(this DateTime value)
    {        
        DateTime now = DateTime.Now; //maybe UtcNow if you're into that

        TimeSpan span = new TimeSpan(now.Ticks - value.Ticks);
        double seconds = Math.Abs(ts.TotalSeconds);

        if (seconds < 60)
            return string.Format("{0} seconds ago", span.Seconds);

        if (seconds < 2700)
            return string.Format("{0} minutes ago", span.Minutes);

        if (seconds < 86400)
            return string.Format("{0} hours ago", span.Hours);

        // repeat for greater "ago" times...
    }
}

Then make your call on your DateTime value like so:

myDateTime.ToRelative();
hunter
  • 62,308
  • 19
  • 113
  • 113
  • Is it possible to bind a datagrid column in asp.net to TimeStarted.ToAgo()? – sprocket12 Dec 10 '12 at 17:03
  • should be, though you may have to do that in an `ItemDataBound` event. Is this windows or web? – hunter Dec 10 '12 at 17:14
  • 1
    If you don't use UTC or `DateTimeOffset`, you're asking for trouble here. Even if all values were produced in the same timezone, you'll have inaccurate answers around daylight savings time changes. Also - by using `Math.Abs`, you are excluding future dates that you might want to say "from now" instead of "ago" – Matt Johnson-Pint Dec 12 '12 at 17:27
  • @MattJohnson, it's just an example, clearly it is incomplete. Good points, though. – hunter Dec 12 '12 at 17:30
  • @hunter agreed. Good example, just want to make sure the OP understands context is important with dates. Thanks. – Matt Johnson-Pint Dec 12 '12 at 17:43