Calculate Time Ago with C#
Tags: csharp, dotnet, beginners, programming
Published: 2022-09-29 14:20:47

![Calculate Time Ago with C#](https://images.unsplash.com/photo-1578337834280-0cbc7fcec092?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxMTc3M3wwfDF8c2VhcmNofDN8fGRpZ2l0YWwlMjBjbG9ja3xlbnwwfHx8fDE2NjQwNzY0OTM&ixlib=rb-1.2.1&q=80&w=2000)

Here is a small extension method over _System.DateTime_ that gives its relative time readable for humans, such as:

- one minute ago
- 2 minutes ago
- one hour ago
- 3 hours ago
- 3 days ago

Check out this extension method over the _DateTime_ structure using switch patterns.

```csharp
public static string AsTimeAgo(this DateTime dateTime)
{
    TimeSpan timeSpan = DateTime.Now.Subtract(dateTime);

    return timeSpan.TotalSeconds switch
    {
        <= 60 => $"{timeSpan.Seconds} seconds ago",

        _ => timeSpan.TotalMinutes switch
        {
            <= 1 => "about a minute ago",
            < 60 => $"about {timeSpan.Minutes} minutes ago",
            _ => timeSpan.TotalHours switch
            {
                <= 1 => "about an hour ago",
                < 24 => $"about {timeSpan.Hours} hours ago",
                _ => timeSpan.TotalDays switch
                {
                    <= 1 => "yesterday",
                    <= 30 => $"about {timeSpan.Days} days ago",

                    <= 60 => "about a month ago",
                    < 365 => $"about {timeSpan.Days / 30} months ago",

                    <= 365 * 2 => "about a year ago",
                    _ => $"about {timeSpan.Days / 365} years ago"
                }
            }
        }
    };
}
```

_Extension method AsTimeAgo_

## Bonus! Different solutions for the same problem

Surfing the web - I'm so old - I found two more solutions for the same problem.

Tell me in the comments section which one you like the best.

### First Solution

```csharp
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;

var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);

if (delta < 1 * MINUTE)
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";

if (delta < 2 * MINUTE)
  return "a minute ago";

if (delta < 45 * MINUTE)
  return ts.Minutes + " minutes ago";

if (delta < 90 * MINUTE)
  return "an hour ago";

if (delta < 24 * HOUR)
  return ts.Hours + " hours ago";

if (delta < 48 * HOUR)
  return "yesterday";

if (delta < 30 * DAY)
  return ts.Days + " days ago";

if (delta < 12 * MONTH)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  return years <= 1 ? "one year ago" : years + " years ago";
}

```

_Found on https://stackoverflow.com/questions/11/calculate-relative-time-in-c-sharp_

### Second Solution

```csharp
public static string TimeAgo(this DateTime dateTime)
{
    string result = string.Empty;
    var timeSpan = DateTime.Now.Subtract(dateTime);

    if (timeSpan <= TimeSpan.FromSeconds(60))
    {
        result = string.Format("{0} seconds ago", timeSpan.Seconds);
    }
    else if (timeSpan <= TimeSpan.FromMinutes(60))
    {
        result = timeSpan.Minutes > 1 ? 
            String.Format("about {0} minutes ago", timeSpan.Minutes) :
            "about a minute ago";
    }
    else if (timeSpan <= TimeSpan.FromHours(24))
    {
        result = timeSpan.Hours > 1 ? 
            String.Format("about {0} hours ago", timeSpan.Hours) : 
            "about an hour ago";
    }
    else if (timeSpan <= TimeSpan.FromDays(30))
    {
        result = timeSpan.Days > 1 ? 
            String.Format("about {0} days ago", timeSpan.Days) : 
            "yesterday";
    }
    else if (timeSpan <= TimeSpan.FromDays(365))
    {
        result = timeSpan.Days > 30 ? 
            String.Format("about {0} months ago", timeSpan.Days / 30) : 
            "about a month ago";
    }
    else
    {
        result = timeSpan.Days > 365 ? 
            String.Format("about {0} years ago", timeSpan.Days / 365) : 
            "about a year ago";
    }

    return result;
}

```

_Found on https://dotnetthoughts.net/time-ago-function-for-c/_

## ❤️ Enjoy this article?

**Forward to a friend** and let them know.  
Leave a comment with questions or improvements.