Reputation: 11
I have table with datetime filed, I want all record which datetime less than datetime now using linq to SQL
var list =db.MyTable.Where(t => t.Date < DateTime.Today).ToList()
Upvotes: 0
Views: 4445
Reputation: 19296
You should use DateTime.Now
property in the condition.
Difference between DateTime.Today
and DateTime.Now
:
DateTime.Today
(msdn):
Gets the current date.
DateTime.Now
(msdn):
Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
Let's say that we run your query at 18:33:15 on 18 February 2015.
If you use DateTime.Today
, the sql query will be:
SELECT * FROM MyTable t WHERE t.Date < '2015-02-18 00:00:00'
And if you use DateTime.Now
, the sql query will be:
SELECT * FROM MyTable t WHERE t.Date < '2015-02-18 18:33:15'
Example:
Sample data:
1 test1 2015-02-18 18:22:13.000
2 test2 2015-02-17 18:24:56.000
3 test3 2015-02-18 13:25:05.000
4 test4 2015-02-20 18:29:48.000
If you use .Where(t => t.Date < DateTime.Today)
the result will be:
2 test2 2015-02-17 18:24:56.000
If you use .Where(t => t.Date < DateTime.Now)
the result will be:
1 test1 2015-02-18 18:22:13.000
2 test2 2015-02-17 18:24:56.000
3 test3 2015-02-18 13:25:05.000
Upvotes: 1