1

I have issutime table in my database and it has the following format:

enter image description here

When i perform search by exact date and time i am getting the results. But what i want is to perform search only with date. For example: 2014-02-28 should return all the results with that date.

This is my code:

var date = Convert.ToDateTime(search);
return View(db.newsletter.Where(x => x.issuetime == date).ToList());

Any idea?

thatthing
  • 676
  • 3
  • 15
  • 39

3 Answers3

2

This is similar to Kosar's approach, but simpler. It should also correctly handle events that occur during the last second of the day.

var date = Convert.ToDateTime(search).Date;
var nextDay = date.AddDays(1);
return View(db.newsletter
    .Where(x => x.issuetime >= date && x.issuetime < nextDay)
    .ToList());

Michael Dunlap's approach would work in LINQ-to-SQL, but LINQ to Entities seems to be unable to handle it. Entity Framework has TruncateTime (see here, but EntityFunctions appears to be deprecated, so I don't think I'd advise using it.

Community
  • 1
  • 1
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
1

Use the Date attribute of the DateTime class.

var date = Convert.ToDateTime(search);
return View(db.newsletter.Where(x => x.issuetime.Date == date.Date).ToList());
Michael Dunlap
  • 4,300
  • 25
  • 36
  • 1
    @ŞenolŞahin: This would work on LINQ to SQL. Perhaps you should include information about your LINQ provider (Entity Framework?) in the original question. – StriplingWarrior Jun 13 '14 at 21:52
1

When you search only with Date, it changes the time stamp for the date to 00:00:00:000. for example for 2014-02-28, it looks for 2014-02-28 00:00:00:000, however what you are looking for is all records with issuetime equal, greater than 2014-02-28 00:00:00:000 and less than 2014-02-29 00:00:00:000. You could try something like this if Michael solution doesn't work for you.

var date1=DateTime.Parse(date + " " + "00:00:00 AM")
var date2=DateTime.Parse(date + " " + "11:59:59 PM")
return View(db.newsletter.Where(x => x.issuetime>= date1 && x.issuetime<= date2).ToList());
Ali
  • 478
  • 4
  • 10