Standing on the shoulders of giants. RSS 2.0
# Tuesday, April 29, 2008

Sample code to get the first day of the week given a date and a DateTimeFormatInfo.

public static DateTime StartOfWeek(DateTime date, DateTimeFormatInfo dateTimeFormat) {

    Debug.Assert(dateTimeFormat != null, "dateTimeFormat != null");
    if (dateTimeFormat == null) {
        throw new ArgumentNullException("dateTimeFormat");
    }

    DayOfWeek currentDay = date.DayOfWeek;
    DayOfWeek firstDay = dateTimeFormat.FirstDayOfWeek;

    int difference = (int)firstDay - (int)currentDay;

    // we always have to move back, 
    // since we're interested in the first day of the week
    if (difference > 0) { difference -= 7; }

    return date.AddDays(difference);
}

 

The attached sourcefile contains the testcases. StartOfCurrentWeek.cs.txt

Tuesday, April 29, 2008 9:47:31 AM (W. Europe Daylight Time, UTC+02:00)  #    Comments [0] - Trackback
Codesnippet
Comments are closed.
About
© Copyright 2008
Paul van Brenk
Sign In
newtelligence dasBlog 2.3.8275.16006
All Content © 2008, Paul van Brenk
DasBlog theme 'Business' created by Christoph De Baene (delarou)