Reputation: 104
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?
Upvotes: 0
Views: 6367
Reputation: 132
I used Calendar.GetWeekOfYear which is in the System.Globalization namespace.
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
DateTime specifiedDate = DateTime.Now;
Calendar cal = dfi.Calendar;
int weekNo = cal.GetWeekOfYear(specifiedDate, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
var dataForWeek = data.Where(x => cal.GetWeekOfYear(x.DeliveryDate.Value, dfi.CalendarWeekRule, dfi.FirstDayOfWeek) == weekNo);
Upvotes: 0
Reputation: 42384
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
Upvotes: 1
Reputation: 22887
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
Upvotes: 1