![](https://i0.wp.com/niteshkejriwal.com/wp-content/uploads/2014/05/c-sharp-tips-tricks1.png?resize=125%2C100&ssl=1)
How To Convert a Date Time to “X minutes ago” in C#
Friends,
In one of our previous post, we saw how can we convert a Date Time value to “X Minutes Ago” feature using jQuery. Today, in this post we will see how we can achieve the same functionality in C#. In this post we will write a C# function that will take a DateTime as a parameter and return us back the appropriate string. In case you want to convert a future date to a similar string, you can check my post here.
The function to convert DateTime to a “Time Ago” string is as below –
public static string TimeAgo(DateTime dt) { if (dt > DateTime.Now) return "about sometime from now"; TimeSpan span = DateTime.Now - dt; if (span.Days > 365) { int years = (span.Days / 365); if (span.Days % 365 != 0) years += 1; return String.Format("about {0} {1} ago", years, years == 1 ? "year" : "years"); } if (span.Days > 30) { int months = (span.Days / 30); if (span.Days % 31 != 0) months += 1; return String.Format("about {0} {1} ago", months, months == 1 ? "month" : "months"); } if (span.Days > 0) return String.Format("about {0} {1} ago", span.Days, span.Days == 1 ? "day" : "days"); if (span.Hours > 0) return String.Format("about {0} {1} ago", span.Hours, span.Hours == 1 ? "hour" : "hours"); if (span.Minutes > 0) return String.Format("about {0} {1} ago", span.Minutes, span.Minutes == 1 ? "minute" : "minutes"); if (span.Seconds > 5) return String.Format("about {0} seconds ago", span.Seconds); if (span.Seconds < = 5) return "just now"; return string.Empty; }
You can call the function something like below-
Console.WriteLine(TimeAgo(DateTime.Now)); Console.WriteLine(TimeAgo(DateTime.Now.AddMinutes(-5))); Console.WriteLine(TimeAgo(DateTime.Now.AddMinutes(-59))); Console.WriteLine(TimeAgo(DateTime.Now.AddHours(-2))); Console.WriteLine(TimeAgo(DateTime.Now.AddDays(-5))); Console.WriteLine(TimeAgo(DateTime.Now.AddMonths(-3)));
The output looks something like below –
Hope this post helps you. Keep learning and sharing!