Sometimes you need to show date in a “Due in X-days” format, not just a date. This will convert date to a string with granularity: Today, tomorrow, yesterday, days, weeks, months.
public static class HumanTime
{
public static string DueDate(DateTime dueDate) {
return DueDate(dueDate, DateTime.Now);
}
public static string DueDate(DateTime dueDate, DateTime dateNow) {
DateTime nowDate = dateNow;
TimeSpan ts = nowDate - dueDate;
if (dueDate.Date == DateTime.Today)
{
return "due today";
}
if (dueDate.Date == DateTime.Now.AddDays(1).Date)
{
return "due tomorrow";
}
if (dueDate.Date == DateTime.Now.AddDays(-1).Date)
{
return "was due yesterday";
}
int totalDays = (int)Math.Round(ts.TotalDays);
if (Math.Abs(totalDays) < 7)
{
return DueStringFormat(totalDays, "day");
}
int weeks = (int)Math.Round( ts.TotalDays / 7 );
if (Math.Abs(weeks) < 5 && Math.Abs(totalDays)<30 )
{
return DueStringFormat(weeks, "week");
}
int months = (int)Math.Round( ts.TotalDays / 30 );
return DueStringFormat(months, "month");
}
public static string DueStringFormat(int count, string unit)
{
string format = "{0} {1}";
if (count < 0)
{
format = "due in {0} {1}";
}
else
{
format = "{0} {1} overdue";
}
return String.Format(format, Math.Abs(count), unit.Quantify(count));
}
/// Adds "s" suffix to a word if there are more than one thing involved.
public static string Quantify(this String singular, int count)
{
int abs = Math.Abs(count);
if (abs > 1)
return singular+"s";
else
return singular;
}
}