我正在尝试从数据库中获取日期的一周,并将其与DateTimePicker中的用户选择值进行比较。我的用户可以选择一天,我写了一个类,以1到52的形式给我当天的那一周。我试图选择获取LINQ来比较数据库中给定日期的周数和由用户。例如:
var report = (from orders in Context.Orders
where DateEx.ISOWeekNumber(orders.Date) ==
DateEx.ISOWeekNumber(datepicker1.Value)
select orders);
但它根本不起作用,因为LINQ没有ISOWeekNumber的翻译。 谁知道我怎么能这样做?
答案 0 :(得分:1)
之类的东西呢?
Math.Truncate(date.DayOfYear/7) +1
给你:
var report = (from orders in Context.Orders
where Math.Truncate(orders.Date.DayOfYear/7) + 1 ==
Math.Truncate(datepicker1.Value.DayOfYear/7) + 1
select orders);
希望有所帮助,
丹
可能将Math.Truncate(date.DayOfYear / 7)带入新的DateEx类
答案 1 :(得分:1)
您可以编写一个完全符合您需要的C#方法。关于LINQ的一个好处是,在编写查询时,如何使用完整编程语言的所有工具。
谷歌快速搜索“isoweeknumber c#”了:
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;
}
}
来源:http://codebetter.com/blogs/peter.van.ooijen/archive/2005/09/26/132466.aspx
答案 2 :(得分:0)
我使用了System.Globalization命名空间中的Calendar.GetWeekOfYear。
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);