Jak ustawić DateTime na pierwszy dzień miesiąca w C #?
Jak ustawić DateTime na pierwszy dzień miesiąca w C #?
Odpowiedzi:
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year,now.Month,1);
DateTime.Noww zmiennej i używaj jej, jeśli zamierzasz używać tej wartości wielokrotnie. Istnieje niewielka szansa na błąd, jeśli ten kod zostanie wykonany dokładnie około północy; dwa wezwania DateTime.Nowmogą wystąpić po obu stronach północy, powodując prawdopodobnie dziwne efekty.
Coś takiego by zadziałało
DateTime firstDay = DateTime.Today.AddDays(1 - DateTime.Today.Day);
public static DateTime FirstDayOfMonth(this DateTime current)
{
return current.AddDays(1 - current.Day);
}
Trochę za późno na imprezę, ale oto metoda przedłużenia, która załatwiła mi sprawę
public static class DateTimeExtensions
{
public static DateTime FirstDayOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1);
}
}
Właśnie stworzyłem kilka metod rozszerzających opartych na odpowiedzi Nicka, a inne na SO
public static class DateTimeExtensions
{
/// <summary>
/// get the datetime of the start of the week
/// </summary>
/// <param name="dt"></param>
/// <param name="startOfWeek"></param>
/// <returns></returns>
/// <example>
/// DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
/// DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
/// </example>
/// <remarks>http://stackoverflow.com/a/38064/428061</remarks>
public static System.DateTime StartOfWeek(this System.DateTime dt, DayOfWeek startOfWeek)
{
var diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
diff += 7;
return dt.AddDays(-1 * diff).Date;
}
/// <summary>
/// get the datetime of the start of the month
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
/// <remarks>http://stackoverflow.com/a/5002582/428061</remarks>
public static System.DateTime StartOfMonth(this System.DateTime dt) =>
new System.DateTime(dt.Year, dt.Month, 1);
/// <summary>
/// get datetime of the start of the year
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static System.DateTime StartOfYear(this System.DateTime dt) =>
new System.DateTime(dt.Year, 1, 1);
}
Powinno to być wydajne i poprawne:
DateTime RoundDateTimeToMonth(DateTime time)
{
long ticks = time.Ticks;
return new DateTime((ticks / TimeSpan.TicksPerDay - time.Day + 1) * TimeSpan.TicksPerDay, time.Kind);
}
Tutaj ticks / TimeSpan.TicksPerDayzwraca liczbę pełnych dni do podanej timei - time.Day + 1resetuje tę liczbę do początku miesiąca.
var currentDate = DateTime.UtcNow.Date;
var startDateTimeOfCurrentMonth = currentDate.AddDays(-(currentDate.Day - 1));