As stated in the question I am attempting to do a date comparison for tasks that are done within a specific date range.
My model has a boolean called "Done" and a string that stores dates of completion called "DatesCompleted"
I currently have a query on that shows me all Done items limited to 25 and it works just fine:
return db.QueryAsync<Tasks>("SELECT * FROM [Tasks] WHERE [Done] = 1 LIMIT 25");
How can I get only dates completed that are 7 days prior to today? This is kind of sudo code how I'd expect to get the solution but I don't know how to write it out in SQLite-net-pcl,
return db.QueryAsync<Tasks>("SELECT * FROM [Tasks] WHERE [Done] = 1 AND [DatesCompleted] >= (DateTime.Now - new TimeSpan(7,0,0,0))` LIMIT 25");
Edit:
After attempting the first solution I am having no luck, all items regardless of completion time appear to show up. I tried this:
foreach(var ii in TaskListDoneSource)
{
System.Diagnostics.Debug.WriteLine(ii.Name + " completed on : " + ii.DateCompleted + " compared against " + (DateTime.Now-new TimeSpan(7,0,0,0)).ToString());
if (ii.DateCompleted > (DateTime.Now - new TimeSpan(7, 0, 0, 0)))
System.Diagnostics.Debug.WriteLine("The date completed has not quite hit 7 days");
}
The IF statement shows me that it is working when I am within 7 days but outside obviously no IF statement call. So that tells me I'm doing something wrong with the query recommended in first answer:
SELECT * FROM [Tasks] WHERE [Done] = 1 AND [DateCompleted] >=
datetime('now', '-7 day')
EDIT 2: I got it working with that query provided. Only thing that was off was off was having the DateCompleted as a DateTime instead of a string that was formatted properly in my model. (https://www.sqlite.org/lang_datefunc.html)
Assuming that in [DatesCompleted] you store timestamps in ISO format YYYY-MM-DD hh:mm:ss, the correct SQLite syntax to get a timestamp exactly 7 days before the current timestamp is:
datetime('now', '-7 day')
or:
datetime('now', '-7 day', 'localtime')
to get the timestamp in local time.
so your query should be:
SELECT *
FROM [Tasks]
WHERE [Done] = 1 AND [DatesCompleted] >= datetime('now', '-7 day')
Related
I am running a SQL-Query in C# using Dapper & DapperQueryBuilder.
using Dapper;
using DapperQueryBuilder;
I use startDate and endDate as lower and upper date limit, since I am not interested in entries that are fare in past.
string startDate = DateTime.Now.AddDays(-14).ToString("MM/dd/yyyy");
string endDate = DateTime.Now.ToString("MM/dd/yyyy");
The query looks as following:
var originalData = cn.QueryBuilder($#"
SELECT TOP 10000
dbo.BEOLStatus_SelCol.Priority,
dbo.BEOLStatus_SelCol.Stage,
dbo.BEOLStatus_SelCol.Batch,
dbo.BEOLStatus_SelCol.Product_Name,
dbo.BEOLStatus_SelCol.DInStage
FROM dbo.BEOLStatus_SelCol
WHERE (((dbo.BEOLStatus_SelCol.Priority) Like {Priority})
AND ((dbo.BEOLStatus_SelCol.Stage) Is Not Null)
AND ((dbo.BEOLStatus_SelCol.Batch) Is Not Null)
AND ((dbo.BEOLStatus_SelCol.Product_Name) Is Not Null)
AND ((dbo.BEOLStatus_SelCol.DInStage) Is Not Null)
AND ((dbo.BEOLStatus_SelCol.StageNo) Like {StageNo})
AND ((dbo.BEOLStatus_SelCol.DInStage) >= {startDate})
AND ((dbo.BEOLStatus_SelCol.DInStage) <= {endDate}))
ORDER BY dbo.BEOLStatus_SelCol.Priority").Query();
I also tried the following one:
var originalData = cn.QueryBuilder($#"
SELECT TOP 10000
dbo.BEOLStatus_SelCol.Priority,
dbo.BEOLStatus_SelCol.Stage,
dbo.BEOLStatus_SelCol.Batch,
dbo.BEOLStatus_SelCol.Product_Name,
dbo.BEOLStatus_SelCol.DInStage
FROM dbo.BEOLStatus_SelCol
WHERE (((dbo.BEOLStatus_SelCol.Priority) Like {Priority})
AND ((dbo.BEOLStatus_SelCol.Stage) Is Not Null)
AND ((dbo.BEOLStatus_SelCol.Batch) Is Not Null)
AND ((dbo.BEOLStatus_SelCol.Product_Name) Is Not Null)
AND ((dbo.BEOLStatus_SelCol.DInStage) Is Not Null)
AND ((dbo.BEOLStatus_SelCol.StageNo) Like {StageNo})
AND ((dbo.BEOLStatus_SelCol.DInStage) Between {startDate} and {endDate}))
ORDER BY dbo.BEOLStatus_SelCol.Priority").Query();
I can see 7 datasets in the database that fit the following criteria:
Priority
StageNo
between startDate = 09.16.2022 and endDate = 09.30.2022
6 out of the 7 datasets get returned as expected, but one is missing.
The one dataset missing looks as following:
Priority = 3
StageNo = 149
DInStage = 09.30.2022 (#)
(#) actually 30.09.2022 because the database is located in Europe, but based on the other 6 datasets returning I assume it gets internally converted and seems to be working
I figured out that if I change endDate = DateTime.Now.ToString("MM/dd/yyyy") to DateTime.Now.AddDays(+1).ToString("MM/dd/yyyy") I get the 7 datasets that I want.
DInStage >= startDate and DInStage <= endDate also seem to make sense to me.
Does anybody see where I did a mistake that causes this one day off? Why do I need to add one additional day? I notice the same behaviour when using the same query in MS Access.
I assume the same is true for dateStart, but I haven't specifically checked that yet.
I think I figured out the reason:
I thought that by using ToString("MM/dd/yyyy") I would be solely comparing the Date of startDate/endDate with DInStage
But actually the Time is still considered during the >=/<=/Between
So I switched to ToString("MM/dd/yyyy HH:mm:ss") instead which solved the problem for me.
I am using now:
startDate = DateTime.Now.AddDays(-14).ToString("MM/dd/yyyy HH:mm:ss");
endDate = DateTime.Now.AddDays(0).ToString("MM/dd/yyyy HH:mm:ss");
So I think when using this new code now I am actually using the timespan between (lets assume for simplicity that its rn 09:00 on 30.09.2022):
startDate = 16.09.2022 09:00:00
endDate = 30.09.2022 09:00:00
So to be entirely correct I would need to set the 09:00:00 to 00:00:00/23:59:59 in order to get a 100% accurate result. But for my use case that's already close enough.
I assume it can be solved by following the provided solution found at How to change time in DateTime?, but I haven't actually verified it.
I have a requirement for generating report in form of 15 days,30 days,45 days.
I have to compare the list data which is coming from db with current date.example if difference is 5days. It is less than 15,so i should send to 15 days ,if >15 i should send to greater than 15etc.How to write linq query for this.can any one help on this please
I'm not sure that can be possible to make this in only one query.
But, I can propose you another solution.
Instead of one query, you can use one query for every case.
In order to compare date difference, you can use SqlFunctions Class.
For this, you should use :
using System.Data.Objects.SqlClient;
Here is the query for 5 days with an imaginary table and fields :
var lstDiff5 = (from ro in dc.Commandes where
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) <= 5
select ro).ToList();
The DateDiff Function takes the date part (DD for days), the start date and the end date. In my case the start date is the current date.
And for 15 days :
var lstDiff15 = (from ro in dc.Commandes where
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) > 5 &&
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) >= 15
select ro).ToList();
You can change the operators > et >= depending your need.
At the end, you can fill your report using all of your lists or you can merge your lists into a new list in order to bind your report to your final list.
You can use DaysBetween function in linq.It will return all dates betwee the given dates.
Example:
DateTime dt = DateTime.Today.Date.AddMonths(1);
int d = dt.DaysBetween(DateTime.Today).ToList().Count;
I am using Simple.Data (version 0.19.0.0) against a SQL Server back end database and would like a query such as the one below to take 25 days from a date to compare against the date now;
DateTime dtNow = DateTime.Now.Date;
var pool = db.Pools.FindAll(db.Pools.Status == 1
&& db.Pools.EndDate - 25 > dtNow)
.Select(db.Pools.AllColumns());
I have tried using DATEADD but get an error that the function is not recognised, I guess because the column name is not the first parameter of the method.
Is this kind of thing possible in Simple.Data, or should I ignore the date in the query and perform the check in a foreach loop following?
Thanks in advance.
Try like that;
DateTime dtNow = DateTime.Now.AddDays(-25).Date;
var pool = db.Pools.FindAll(db.Pools.Status == 1
&& db.Pools.EndDate > dtNow)
.Select(db.Pools.AllColumns());
I overcame the problem by using a where clause on my query with a >= and < date range as suggested in how to search by date question.
I would like to retrieve the data between 1 -30 of the current month [ i am using MSACCESS Dbase to do so] Below is the query that i am trying --
SELECT count(usercategory) as category_count ,usercategory FROM user_category
where IssueDate between DATEADD('m', DATEDIFF('m', 0, DATE()) - 0 , 0) and DATEADD('m', DATEDIFF('m', 0, DATE()) + 1, - 1 ) group by usercategory
Data that i am holding in my MSACCESS Dbase -
Category1 9/7/2013 12:00:00 AM
Category1 9/8/2013 12:00:00 AM
Category2 10/8/2013 12:00:00 AM
so output should have only 2 records
but my query is giving no results
Here is the query I think you need. All the functions it uses are always available in Access SQL regardless of whether the query is run from within an Access session or from without (as in your c# situation).
The db engine will evaluate both those DateSerial expressions once, then use their results to filter the result set. This approach will be especially fast with an index on IssueDate.
SELECT
Count(usercategory) AS category_count,
usercategory
FROM user_category
WHERE
IssueDate >= DateSerial(Year(Date()), Month(Date()), 1)
AND IssueDate < DateSerial(Year(Date()), Month(Date()) + 1, 0)
GROUP BY usercategory;
Here is an Access Immediate window session which explains the logic for those DateSerial expressions ...
? Date()
9/6/2013
? Year(Date())
2013
? Month(Date())
9
' get the date for first of this month ...
? DateSerial(Year(Date()), Month(Date()), 1)
9/1/2013
' now get the date for the last of this month ...
? DateSerial(Year(Date()), Month(Date()) + 1, 0)
9/30/2013
I tried to test the month of the staff working whether equal 3 months from they started work till now. And this is what I am trying to use :
int totalMonth = 3;
int totalYear = 0;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
//block of code that I used LinQ to Entity to get staff start work date
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
The format of date in my database is 07/05/2012 But I got the error :
startIndex cannot be larger than length of string. Parameter name: startIndex
Could any one tell me , what did I wrong here? Thanks in advanced.
The format of date in my database is 07/05/2012
Most likely the date is stored as binary and has no format. And what you see when listing the records could be different from what happens in C#.
Use the debugger to find out what result.First().StartDate actually looks like. Could be "5-7-12".