Skip to content

Instantly share code, notes, and snippets.

@morbidcamel101
Last active August 29, 2015 14:11
Show Gist options
  • Save morbidcamel101/427e749b4469df9469ed to your computer and use it in GitHub Desktop.
Save morbidcamel101/427e749b4469df9469ed to your computer and use it in GitHub Desktop.
GMail and iCloud style Date Formatting
public enum TimeFormat
{
Auto,
IfPresent,
Always,
Today,
Never
}
public static class DateExtensions
{
const string DefaultDateFormat = "{0:MM/dd/yyyy}";
const string DefaultDateNoYearFormat = "{0:dd MMM}";
const string DefaultWeekDateFormat = "{0:ddd}";
const string DefaultDateTimeFormat = "{0:dd MMM yyyy hh:mm tt}";
const string DefaultTimeFormat = "{0:hh:mm tt}";
public static DateTime GetStartOfWeek(this DateTime dateTime)
{
DayOfWeek day = dateTime.DayOfWeek;
int days = day - DayOfWeek.Monday;
return dateTime.AddDays(-days);
}
public static DateTime GetEndOfWeek(this DateTime dateTime)
{
DayOfWeek day = dateTime.DayOfWeek;
int days = DayOfWeek.Saturday - day;
return dateTime.AddDays(days);
}
public static string ToDisplayText(this DateTime dateTime, TimeFormat timeFormat = TimeFormat.Auto)
{
StringBuilder builder = new StringBuilder();
if (DateTime.Today != dateTime.Date)
{
//TimeSpan elapsed = (DateTime.Now - dateTime);
if (dateTime >= DateTime.Today.GetStartOfWeek() && dateTime <= DateTime.Today.GetEndOfWeek())
builder.AppendFormat(DefaultWeekDateFormat, dateTime);
else
builder.AppendFormat(dateTime.Year == DateTime.Today.Year
? DefaultDateNoYearFormat
: DefaultDateFormat, dateTime);
}
switch (timeFormat)
{
case TimeFormat.Auto: // In auto mode we use the Today Logic
case TimeFormat.Today:
if (dateTime.Date == DateTime.Today && dateTime.TimeOfDay.TotalSeconds > 0.0)
goto case TimeFormat.Always;
break;
case TimeFormat.IfPresent:
if (dateTime.TimeOfDay.TotalSeconds > 0.0)
goto case TimeFormat.Always;
break;
case TimeFormat.Always:
builder.Append(' ');
builder.AppendFormat(DefaultTimeFormat, dateTime);
break;
case TimeFormat.Never:
break;
}
return builder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment