Programming  /  C# June 26, 2009

Getting the first day in a week with C#

I recently found myself having a DateTime value and needing to calculate the date of the first day in the week that my known date was in using C#. While this is one of those things that are pretty simple to do once you know the solution it did take me a couple of hours to get it right. It turns out that something as simple as calculating a the first day of a week is trickier than one might expect, at least if we want a solution that works for all cultures.

My first instinct was to calculate the first day of a week by subtracting dayInWeek.DayOfWeek - firstDayInWeek days from dayInWeek where dayInWeek is a DateTime specifying a date in the week. That worked fine as long as I did the calculations in an environment where the culture was English, where the first day of the week is Sunday which is enumerated as 0 in DayOfWeek (against international standards which says the first day of the week is monday). As I shifted to using a Swedish culture it broke down and I had to find a better solution.

Heres what I finally came up with:

using System;
using System.Globalization;

public static class FirstDayOfWeekUtility
{
    /// <summary>
    /// Returns the first day of the week that the specified
    /// date is in using the current culture. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek)
    {
        CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;
        return GetFirstDateOfWeek(dayInWeek, defaultCultureInfo);
    }

    /// <summary>
    /// Returns the first day of the week that the specified date 
    /// is in. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek, CultureInfo cultureInfo)
    {
        DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
        DateTime firstDayInWeek = dayInWeek.Date;
        while (firstDayInWeek.DayOfWeek != firstDay)
            firstDayInWeek = firstDayInWeek.AddDays(-1);

        return firstDayInWeek;
    }
}

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more

Comments

comments powered by Disqus

More about C#