Help, please, filter the data by date of month and day. There are some objects with the date of creation. One must choose a range from month: day to month: day. I choose and compare the dates of the month and day ... but if, for example, I choose January 20 and March 30, the data between March 1 - 20 - February will be lost.
1 answer
The DateTime type supports the comparison of its instances with each other. That is, if I understand the question correctly, there is no need to compare individual properties:
var fromDate = new DateTime(2012, 01, 20, 0, 0, 0); var toDate = new DateTime(2012, 03, 30, 23, 59, 59); var filtered = from element in source where element.Date >= fromDate && element.Date <= endDate select element;
UPD: (based on the discussion in the comments)
var fromDay = (new DateTime(2001, 01, 20, 0, 0, 0)).DayOfYear; var toDay = (new DateTime(2001, 03, 30, 23, 59, 59)).DayOfYear; var filtered = from element in source let dayOfYear = element.Date.DayOfYear let dayOfYearShifted = (dayOfYear > 59 && DateTime.IsLeapYear(element.Date.Year) ? dayOfYear : dayOfYear - 1 where element.Date.DayOfYear >= dayOfYearShifted && element.Date.DayOfYear <= dayOfYearShifted select element;
Some explanations:
- You can use any non-leap year in fromDay and toDay, not necessarily 2001
- dayOfYear> 59 is because if the date is before February 28 inclusive, then you don’t need to take anything off, even if the year is a leap year
- oneThe syntax of the methods is simpler: var filtered = source.Whre (element => element.Date> = fromDate && element.Date <= endDate); - Specter
- Not quite right ... you need not to take the year into account For example, from January 20 to March 31 ... in my way, we will lose February and March to the 20th day ... we need to avoid this and not take the year into account ... it could be from 1990 to 2030 and TP - Sam-Fisher
- onethen compare only DateTime.DayOfYear var filtered = source.Where (element => element.Date.DayOfYear> = fromDate.DayOfYear && element.Date.DayOfYear <= endDate.DayOfYear); - Specter
- oneIs there a problem with (in) leap years when using DayOfYear? - Maxim Kamalov
|