views:

547

answers:

3

I am trying to get the week of a date from the database and compare it to a user selected value from a DateTimePicker. My users can select a day and I wrote a class that gives me the week of that day in the form 1 to 52. I am trying to select get LINQ to compare the weeks of a given date from the database to the week selected by the user. Example:

var report = (from orders in Context.Orders
              where DateEx.ISOWeekNumber(orders.Date) == 
                    DateEx.ISOWeekNumber(datepicker1.Value)
              select orders);

But it is not working at all as LINQ doesn't have a translation for the ISOWeekNumber. Anyone knows how I can do this?

+1  A: 

What about something of the ilk?

Math.Truncate(date.DayOfYear/7) +1

Giving you:

var report = (from orders in Context.Orders
    where Math.Truncate(orders.Date.DayOfYear/7) + 1 ==
    Math.Truncate(datepicker1.Value.DayOfYear/7) + 1
    select orders);

Hope that helps,

Dan

Probably take Math.Truncate(date.DayOfYear/7) into your new DateEx class

Daniel Elliott
You'll need some checking for the 31st of December on a leap year!
Daniel Elliott
Thank you so much. This did the trick. I just need to make sure I catch leap years but it worked perfectly. Thank you again.
yveslebeau
+1  A: 

Looks like someone has a blog post talking about doing this several different ways.

Chris Shaffer
+1  A: 

You could write a C# method that does exactly what you need. One of the nice things about LINQ is how you have all the tools of a full programming language available to you when you write your queries.

A quick Google search for "isoweeknumber c#" turned up this:

private int weekNumber(DateTime fromDate)
{
    // Get jan 1st of the year
    DateTime startOfYear = fromDate.AddDays(- fromDate.Day + 1).AddMonths(- fromDate.Month +1);
    // Get dec 31st of the year
    DateTime endOfYear = startOfYear.AddYears(1).AddDays(-1);
    // ISO 8601 weeks start with Monday
    // The first week of a year includes the first Thursday
    // DayOfWeek returns 0 for sunday up to 6 for saterday
    int[] iso8601Correction = {6,7,8,9,10,4,5};
    int nds = fromDate.Subtract(startOfYear).Days  + iso8601Correction[(int)startOfYear.DayOfWeek];
    int wk = nds / 7;
    switch(wk)
    {
        case 0 :
            // Return weeknumber of dec 31st of the previous year
            return weekNumber(startOfYear.AddDays(-1));
        case 53 :
            // If dec 31st falls before thursday it is week 01 of next year
            if (endOfYear.DayOfWeek < DayOfWeek.Thursday)
                return 1;
            else
                return wk;
        default : return wk;
    }
}

Source: http://codebetter.com/blogs/peter.van.ooijen/archive/2005/09/26/132466.aspx

DanM