Feedback

C# - FirstDayOfWeek

Veröffentlicht von am 7/10/2008
(1 Bewertungen)
Liefert zu einem Datum den ersten Tag der Woche zurück in der das Datum liegt

        /// <summary>
        /// Resolves the first day of the week of the given DateTime value.
        /// </summary>
        /// <param name="source">The given DateTimeValue.</param>
        /// <returns>The DateTime.Date of the first day of the week of the given DateTime value.</returns>
        /// <remarks>If the given DateTime is the first day of the week, then the source.Date will be the result.</remarks>
        public static DateTime FirstDayOfWeek(this DateTime source)
        {
            DayOfWeek day =  source.DayOfWeek;
            DayOfWeek weekBegin = System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek;
            DateTime result;

            if (day >= weekBegin)
            {
                int offSet = day - weekBegin;


                result = source.AddDays(offSet * -1).Date;
            }
            else
            {
                result = source.AddDays(((int)day)-6);
            }

            return result;
        }
Abgelegt unter Woche, Week, Kalender, Calendar, Day, Tag, Montag, Sonntag.

1 Kommentare zum Snippet

Minside schrieb am 6/18/2013:
While the snippet is using localisation for the begin of the week, it doesn't work for abitrary begins of the week.
It works for Mo(1) and Su(0), but not for Tuesday(2) as begin of the week and source = Mo(0). The function uses the else-case and Adds (day-6) calc to (1-6) = -5 to Monday, which results in the preceding Wednesday and not tuesday.

Here is the version, that works:


public DateTime get_FirstDayOfWeek(DateTime source)
{
// Condition - All days of week have corresponding numbers >= 0
// Day is after begin of week -> (day-begin) > 0 -> Subtract day by the difference
// Day is before begin of week -> (day-begin) < 0 -> Subract (7 - |diff|) OR Subract(7+diff)

DayOfWeek day = source.DayOfWeek;
DayOfWeek weekBegin = System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek;
DateTime result;

int offSet = day - weekBegin;
if (day >= weekBegin) // offSet >= 0
{
result = source.AddDays(-offSet).Date;
}
else // offSet < 0
{
result = source.AddDays(-(7 + offSet));
}
return result;
}
 

Logge dich ein, um hier zu kommentieren!