#region Human Friendly Dates
///
///
///
///
///
public static string ToHumanFriendlyDate(this DateTime date, bool neverShowSeconds = true)
{
TimeSpan ts = DateTime.Now.Subtract(date);
return ToHumanFriendlyDate(ts, neverShowSeconds);
}
///
///
///
///
///
public static string ToHumanFriendlyDate(this DateTime? date, bool neverShowSeconds = true)
{
if (date == null)
return null;
return ToHumanFriendlyDate(date.Value, neverShowSeconds);
}
///
///
///
///
///
public static string ToHumanFriendlyDate(this TimeSpan timespan, bool neverShowSeconds = true)
{
/* Examples of conversions:
* < 1m : Less than a minute [ago|to go]
* 1: A minute [ago|to go]
* 2: A couple minutes [ago|to go]
* 3-4: A few minutes [ago|to go]
* 5+: [min] minutes [ago|to go]
* 1 hour: An hour ago/to go
* 2 hours: A couple hours [ago/to go]
* Yesterday: Yesterday at 12:30 PM
* Tomorrow: Tomorrow at 12:30 pm
*/
bool isInFuture = timespan.TotalMinutes != Math.Abs(timespan.TotalMinutes);
Func endQualifier = () => isInFuture ? "to go" : "ago";
Func formatDateFunc = date => date.ToShortDateString().Replace("/" + DateTime.Now.Year, "");
if (Math.Abs(timespan.TotalSeconds) < 5)
{
return "A few seconds " + endQualifier();
}
else if (Math.Abs(timespan.TotalSeconds) < 60)
{
return "Less than a minute " + endQualifier();
}
else if (Math.Abs(timespan.TotalMinutes) < 3)
{
return "A couple minutes " + endQualifier();
}
else if (Math.Abs(timespan.TotalMinutes) < 5)
{
return "A few minutes " + endQualifier();
}
else if (Math.Abs(timespan.TotalMinutes) < 55)
{
return timespan.Minutes.ToString() + " minutes " + endQualifier();
}
else if (Math.Abs(timespan.TotalHours) < 1)
{
return "Less than an hour " + endQualifier();
}
else if (Math.Abs(timespan.TotalHours) < 2 && Math.Abs(timespan.Hours) == 1)
{
return "An hour " + endQualifier();
}
else if (Math.Abs(timespan.TotalHours) < 3)
{
return "A couple hours " + endQualifier();
}
else if (Math.Abs(timespan.TotalHours) < 5)
{
return "A few hours " + endQualifier();
}
else
{
string day;
DateTime d = DateTime.Now.Subtract(timespan);
if (Math.Abs(timespan.TotalDays) < 2)
{
if (d.Day DateTime.Now.Day)
{
day = "Tomorrow";
}
else
{
day = "Today";
}
}
else
{
day = formatDateFunc(d);
}
if (neverShowSeconds)
{
return day + ", " + d.ToString("h:mm tt").Replace(":00", "");
}
else
{
return day + ", " + d.ToShortTimeString().Replace(":00", "");
}
}
}
///
///
///
///
///
public static string ToHumanFriendlyDate(this TimeSpan? timespan, bool neverShowSeconds = true)
{
if (timespan == null)
return null;
return ToHumanFriendlyDate(timespan.Value, neverShowSeconds);
}
#endregion