Monday, April 25, 2011

Calculate previous week's start and end date

What is the best way to calculate the previous week's start and end date in C#? I.e. today 18 March would result in 9 March (Monday last week) and 15 March (Sunday last week).

I have seen this done with DayOfWeek and a switch statement to work out an offset but was wondering whether there is a more elegant way.

From stackoverflow
  • DayOfWeek weekStart = DayOfWeek.Monday; // or Sunday, or whenever
    DateTime startingDate = DateTime.Today;
    
    while(startingDate.DayOfWeek != weekStart)
        startingDate = startingDate.AddDays(-1);
    
    DateTime previousWeekStart = startingDate.AddDays(-7);
    DateTime previousWeekEnd = startingDate.AddDays(-1);
    

    Read: Backtrack one day at a time until we're at the start of this week, and then subtract seven to get to the start of last week.

  • Using DayOfWeek would be a way of achieving this:

        DateTime date = DateTime.Now.AddDays(-7);
        while (date.DayOfWeek != DayOfWeek.Monday)
        {
            date = date.AddDays(-1);
        }
    
        DateTime startDate = date;
        DateTime endDate = date.AddDays(7);
    
  • You can skip the while loop and use

    DateTime mondayOfLastWeek = date.AddDays( -(int)date.DayOfWeek - 6 );
    

    This assumes you're using Monday as the first day of the week.

    Austin Salonen : To answer the question, startOfWeek should be named sundayOfLastWeek. "DateTime mondayOfLastWeek = date.AddDays(-(int)date.DayOfWeek - 6);"
    bstoney : Thanks for the correction Austin Salonen
    Henryk : Nice one liner approach. I think the following would then work regardless of which day its run on: mondayOfLastWeek = DateTime.Now.AddDays( -(int)DateTime.Now.DayOfWeek - 6 ); sundayOfLastWeek = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek);
  • using Fluent DateTime http://fluentdatetime.codeplex.com/

            var dateTime = 1.Weeks().Ago();
            var monday = dateTime.Previous(DayOfWeek.Sunday);
            var sunday = dateTime.Next(DayOfWeek.Sunday);
    

0 comments:

Post a Comment