public static DateTime StartOf(this DateTime dt, TimeUnits unit)
{
switch (unit)
{
case TimeUnits.Century:
{
int year = dt.Year / 100 * 100;
return new DateTime(year, 1, 1, 0, 0, 0, dt.Kind);
}
case TimeUnits.Decade:
{
int year = dt.Year / 10 * 10;
return new DateTime(year, 1, 1, 0, 0, 0, dt.Kind);
}
case TimeUnits.Year:
{
return new DateTime(dt.Year, 1, 1, 0, 0, 0, dt.Kind);
}
case TimeUnits.Quarter:
{
int month = (dt.Quarter() - 1) * 3 + 1;
return new DateTime(dt.Year, month, 1, 0, 0, 0, dt.Kind);
}
case TimeUnits.Week:
{
DayOfWeek weekStart = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
int delta = weekStart - dt.DayOfWeek;
return dt.AddDays(delta).StartOf(TimeUnits.Day);
}
case TimeUnits.Month:
{
return new DateTime(dt.Year, dt.Month, 1, 0, 0, 0, dt.Kind);
}
case TimeUnits.Day:
{
return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, dt.Kind);
}
case TimeUnits.Hour:
{
return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0, dt.Kind);
}
case TimeUnits.Minute:
{
return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0, dt.Kind);
}
case TimeUnits.Second:
{
return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Kind);
}
}
throw new Exception("Calculation of start of unit \"{0}\" is not implemented.".SmartFormat(unit));
}