Sprache: C#
Diese statische Klasse besitzt zwei Methoden die zum übergebenen Datum den ersten und den letzten Tag des Monats berechnet.
public static class Month
{
/// <summary>
/// Gets the first day of the month.
/// </summary>
/// <param name="givenDate">The given date.</param>
/// <returns>the first day of the month</returns>
public static DateTime GetFirstDayOfMonth(DateTime givenDate)
{
return new DateTime(givenDate.Year, givenDate.Month, 1);
}
/// <summary>
/// Gets the last day of month.
/// </summary>
/// <param name="givenDate">The given date.</param>
/// <returns>the last day of the month</returns>
public static DateTime GetTheLastDayOfMonth(DateTime givenDate)
{
return GetFirstDayOfMonth(givenDate).AddMonths(1).Subtract(new TimeSpan(1, 0, 0, 0, 0));
}
}
public static class Month
{
/// <summary>
/// Gets the first day of the month.
/// </summary>
/// <param name="givenDate">The given date.</param>
/// <returns>the first day of the month</returns>
public static DateTime GetFirstDayOfMonth(DateTime givenDate)
{
return new DateTime(givenDate.Year, givenDate.Month, 1);
}
/// <summary>
/// Gets the last day of month.
/// </summary>
/// <param name="givenDate">The given date.</param>
/// <returns>the last day of the month</returns>
public static DateTime GetTheLastDayOfMonth(DateTime givenDate)
{
return GetFirstDayOfMonth(givenDate).AddMonths(1).Subtract(new TimeSpan(1, 0, 0, 0, 0));
}
}
Alte URL:
/snippet/ersten-und-letzten-tag-im-monat-berechnen/616
Hey Jan!
Die Methode GetTheLastDayOfMonth ließe sich noch einen Tacken netter gestalten:
[code]
return GetFirstDayOfMonth(givenDate).AddMonths(1).AddDays(-1);
[/code]
Take care,
Patrick
Stimmt, das sieht etwas besser aus, danke für den Hinweis.