Come posso impostare un DateTime sul primo del mese in C #?
Come posso impostare un DateTime sul primo del mese in C #?
Risposte:
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year,now.Month,1);
DateTime.Nowin una variabile e usala se intendi utilizzare il valore ripetutamente. C'è una piccola possibilità di errore nel caso in cui questo codice venga eseguito esattamente intorno a mezzanotte; le due chiamate a DateTime.Nowpossono accadere su entrambi i lati della mezzanotte causando effetti possibilmente strani.
Qualcosa del genere funzionerebbe
DateTime firstDay = DateTime.Today.AddDays(1 - DateTime.Today.Day);
public static DateTime FirstDayOfMonth(this DateTime current)
{
return current.AddDays(1 - current.Day);
}
Un po 'in ritardo per la festa, ma ecco un metodo di estensione che ha funzionato per me
public static class DateTimeExtensions
{
public static DateTime FirstDayOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1);
}
}
Ho appena creato alcuni metodi di estensione basati sulla risposta di Nick e altri su 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);
}
Questo dovrebbe essere efficiente e corretto:
DateTime RoundDateTimeToMonth(DateTime time)
{
long ticks = time.Ticks;
return new DateTime((ticks / TimeSpan.TicksPerDay - time.Day + 1) * TimeSpan.TicksPerDay, time.Kind);
}
Qui ticks / TimeSpan.TicksPerDayrestituisce il conteggio dei giorni interi fino a un dato timee - time.Day + 1reimposta questo conteggio all'inizio del mese.
var currentDate = DateTime.UtcNow.Date;
var startDateTimeOfCurrentMonth = currentDate.AddDays(-(currentDate.Day - 1));