Reputation: 2175
I am struggling for comparing dates in MVC. I tried all the ways but still nothing went well. Seems to very strange.
This is my Datetime textbox bounded with JQuery calendar.
@Html.TextBoxFor(x => x.dateofAction, ViewBag.filterdateTime as string, new { @id = "dateofAction", @placeholder = "Date Of Action", @class = "form-control datepicker validate[required, custom[date,future[min]]]", style = "width:80%;height:20px;" })
This is my Model field.
public DateTime? dateofAction { get; set; }
Finaly this is my query
upld_id = (from c in db.ts_upld_doc where (c.upld_ModifiedDateTime).Value.Year == datemodified.Year select c.upld_docid).ToArray();
I hit breakpoint and checked. I found values as below.
11/10/2016 12:00:00 AM
- User supplied date2016-10-11 13:52:53.583
- Sql table(upld_ModifiedDateTime)I tried in many ways like comparing only day,date,month,year but nothing worked for me. Can some expert tell me why I am having this issue? thank you very much.
Upvotes: 0
Views: 1193
Reputation: 24147
Where is datemodified
declared, and how does it get its value?
If datemodified
is declared and set through your Action method in the Controller, then the parameter name you chose could be the problem.
So this will not work:
// MVC ignores Form field 'dateofAction' because it expects 'datemodified'.
[HttpPost]
ActionResult Index(DateTime datemodified) { ... }
Whereas this should work:
// MVC uses Form field 'dateofAction' to set parameter 'dateofAction'.
[HttpPost]
ActionResult Index(DateTime dateofAction) { ... }
Upvotes: 0
Reputation: 62213
You should be using DbFunctions with EF6.
var dateValue = datemodified.Date;
var upld_id = (
from c in db.ts_upld_doc
where DbFunctions.TruncateTime(c.upld_ModifiedDateTime) == dateValue
select c.upld_docid).ToArray();
If you are using an older version of EF use EntityFunctions
var dateValue = datemodified.Date;
var upld_id = (
from c in db.ts_upld_doc
where EntityFunctions.TruncateTime(c.upld_ModifiedDateTime) == dateValue
select c.upld_docid).ToArray();
Upvotes: 0
Reputation:
Change the query to select the value between the start and end of the day
DateTime start = datemodified.Date;
DateTime end = start.AddDays(1);
upld_id = (from c in db.ts_upld_doc
where c.upld_ModifiedDateTime >= start && c.upld_ModifiedDateTime < end
select c.upld_docid).ToArray();
or
upld_id = db.ts_upld_doc
.Where(c => where c.upld_ModifiedDateTime >= start && c.upld_ModifiedDateTime < end)
.Select(c => c.upld_docid);
Upvotes: 1
Reputation: 210
First remove time from upld_ModifiedDateTime and then use DateTime.Compare method to do the comparision as shown below:
upld_id = (from c in db.ts_upld_doc where
DateTime.Compare(
new DateTime(c.upld_ModifiedDateTime.Year, c.upld_ModifiedDateTime.Month, c.upld_ModifiedDateTime.Day))
,datemodified) == 0
select c.upld_docid).ToArray();
Upvotes: 0