Linq Get 7 days prior to given date - linq

Is it possible to get all 7 days for a given date using linq query, please?
I could use the other methods to populate the list but thought would be wise to use 2 lines of LINQ if possible.
Thanks

Hacky but
IEnumerable<DateTime> getDays(DateTime date) {
return Enumerable.Range(0, 7).Select(n => date.AddDays(-1 * n));
}
Note: didn't test and not positive about the date methods.

Related

Retrieve database records between two weekdays

I have several records in my database, the table has a column named "weekday" where I store a weekday like "mon" or "fri". Now from the frontend when a user does search the parameters posted to the server are startday and endDay.
Now I would like to retrieve all records between startDay and endDay. We can assume startDay is "mon" and endDay is "sun". I do not currently know how to do this.
Create another table with the names of the days and their corresponding number. Then you'd just need to join up your current table with the days table by name, and then use the numbers in that table to do your queries.
Not exactly practical, but it is possible to convert sun,mon,tue to numbers using MySQL.
Setup a static year and week number like 201610 for the 10th week of this year, then use a combination of DATE_FORMAT with STR_TO_DATE:
DATE_FORMAT(STR_TO_DATE('201610 mon', '%X%V %a'), '%w')
DATE_FORMAT(STR_TO_DATE('201610 sun', '%X%V %a'), '%w')
DATE_FORMAT(STR_TO_DATE('201610 tue', '%X%V %a'), '%w')
These 3 statements will evaluate to 0,1,2 respectively.
The main thing this is doing is converting the %a format (Sun-Sat) to the %w format (0-6)
well i don't know the architecture of your application as i think storing and querying a week day string is not appropriate, but i can tell you a work around this.
make a helper function which return you an array of weekdays in the range i-e
function getWeekDaysArray($startWeekDay, $endWeekDay) {
returns $daysArray['mon','tue','wed'];
}
$daysRangeArray = getWeekDaysArray('mon', 'wed');
now with this array you can query in table
DB::table('TableName')->whereIn('week_day', $daysRangeArray)->get();
Hope this help

Oracle DateAdd() of 2 different columns

I'm trying to figure out a DateAdd() equivalent in Oracle that is actually the difference in seconds between 2 columns in the same table:
SELECT
DISTINCT p.packet_id,
p.launch_dt,
r.route_duration,
s.completion_date,
DATEADD(SS, r.route_duration, p.launch_dt) AS tempDate
FROM
tdc_arc_apprpkt_def p
JOIN tdc_arc_inpr_route_def r
ON p.packet_id = r.packet_id
JOIN tdc_arc_inpr_route_step_detai s
ON p.packet_id = s.packet_id
AND s.completion_date > DATEADD(SS, r.route_duration, p.launch_dt)
Any help would be greatly appreciated!
In addition to being able to do date arithmetic using fractions of days as Tony demonstrates, assuming you are using 9i or later, you can also use interval functions (or, even better, define the ROUTE_DURATION column as an interval) and add intervals to dates. In your case, you can do
p.launch_dt + numtodsinterval( r.route_duration, 'SECOND' )
to add route_duration seconds to launch_dt.
If you were to define the route_duration column as an INTERVAL DAY TO SECOND rather than a NUMBER, you could simply add it to a date
p.launch_dt + r.route_duration
If I understand you correctly, you want to add r.route_duration seconds to p.launch_dt? In that case the expression is:
p.launch_dt + (r.route_duration/24/60/60)
Oracle DATE arithmetic works in days, so the divisions by 24, 60 and 60 convert the route_duration value from seconds to days.

How can I compare 2 dates in a Where statement while using NoRM for MongoDB on C#?

I have a table in Mongo. One of the fields is a DateTime. I would like to be able to get all of the records that are only for a single day (i.e. 9/3/2011).
If I do something like this:
var list = (from c in col
where c.PublishDate == DateTime.Now
select c).ToList();
Then it doesn't work because it is using the time in the comparison. Normally I would just compare the ToShortDateString() but NoRM does not allow me to use this.
Thoughts?
David
The best way to handle this is normally to calculate the start datetime and end datetime for the date in question and then query for values in that range.
var start = DateTime.Now.Date;
var end = start.AddDays(1);
...
But you'd also be well advised to switch to the official C# driver now. You should also use UTC datetimes in your database (but that gets more complicated).

Comparing Dates, ignoring year - Linq/Entity Framework

Is there any easy way to compare dates, that ignores year, using Linq and the Entity Framework?
Say I have the following
var result = context.SomeEntity.Where(e => e.SomeDate > startDate);
This is assuming that SomeDate and startDate are .NET DateTime's.
What I would like to do is compare these dates without comparing year. SomeDate can be any year. Is there any easy way to do this? The only way I could think of would be to use the following:
var result = context.SomeEntity(e =>
e.SomeDate.Month > startDate.Month ||
(e.SomeDate.Month == startDate.Month && e.SomeDate.Day >= startDate));
This method quickly gets more complicated if I am looking to have an endDate as well, as I will have to do things like take account for when the start date is at the end of the year and the end date is at the beginning.
Is there any easy way to go about this?
Update:
I ended up just going about it the way I had initially thought in the post... a heck of a lot of code for something conceptually simple. Basically just had to find if a date fell within a range, ignoring year, and looping the calendar if startDate > endDate If anyone knows an easier way, please post as I am still interested.
If you really need to compare only dates (not times) then DateTime.DayOfYear property might help. But you should be careful regarding leap years in this case. Other of this I cannot imagine anything more simple than your approach with comparing months and days.
If all you care about is that this method will become more complicated after introducing second comparison then simple method extraction should help.
Another approach might be creating an extension method which will return a number applicable for your comparison. For example let's call this method GetYearIgnoringOrdinal():
public static int GetYearIgnoringOrdinal(this DateTime date)
{
return date.Month*100 + date.Day;
}
And then use it like this:
var result = context.SomeEntity.Where(e => e.SomeDate.GetYearIgnoringOrdinal() > startDate.GetYearIgnoringOrdinal());
Slightly simpler looking way
var result = context.SomeEntity(e =>
e.SomeDate.Month * 100 + e.SomeDate.Day > startDate.Month * 100 + startDate.Day
);
You could also create a user defined function (assuming SQL server is used) and that function can be used in the query.

Get the the most recent and the one before the most recent item

I have a table with many anniversaries : Date + Name.
I want to display the next anniversary and the one after with Linq.
How can i build the query ?
I use EF
Thanks
John
Just order by date and then use the .Take(n) functionality
Example with a list of some objects assuming you want to order by Date then Name:
List<Anniversaries> annivDates = GetAnnivDates();
List<Anniversaries> recentAnniv = annivDates.OrderBy(d => d.Date).ThenBy(d => d.Name).Take(2).ToList();
If the anniversaries are stored in regular DateTime structs, they may have the 'wrong' year set (i.e. wedding or birth year). I suggest writing a function which calculates the next date for an anniversary (based on the current day) like:
static DateTime CalcNext(DateTime anniversary) {
DateTime newDate = new DateTime(DateTime.Now.Year, anniversary.Month, anniversary.Day);
if (newDate < DateTime.Now.Date)
newDate = newDate.AddYear(1);
return newDate;
}
Then you proceed with sorting the dates and taking the first two values like described in the other postings:
(from e in anniversaries orderby CalcNext(e.Date) select e).Take(2)

Resources