How to display publish time "Ago Time" c#

Snippet for a rather popular requirement. Formatting a date in a nice way, using infamous “time ago” function. This is the basic version which I adapt to fit a specific project. To keep it easily customizable to your needs, I haven’t packaged it up.

Just pass a date to it, and function will return one of the seven possible formats:

  • One second ago - if one second elapsed
  • 10 seconds ago - in more than one seconds elapsed
  • a minute ago - If more than a minute elapsed
  • 15 minutes ago - If more than a minutes elapsed
  • an hour ago - if 60 minutes elapsed
  • 2 hours ago - If more than an 120 minutes elapsed
  • Yesterday - for Yesterday
  • 3 days ago - for more than a day

Feel free to play with it and add more cases if you need them.


private const int SECOND = 1;
private const int MINUTE = 60 * SECOND;
private const int HOUR = 60 * MINUTE;
private const int DAY = 24 * HOUR;
private static string DateTimeFormaterForRecentArticle(DateTime datetime)
{
	var ts = new TimeSpan(DateTime.UtcNow.Ticks - datetime.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";
	return FormatDateTime(datetime);
}

 

Sample Result:

 


Summary: