1) Normalize your Date
column data so that all rows in Logs
are of the same time zone. Best option because you don't have do a conversion in a query which will make the query faster, plus for other reasons like making reports easier to read.
2) Use a sproc or parameterized query in which you convert Date
using the SQL function TODATETIMEOFFSET(<date>,<offset>)
3) If you want to convert it post-query you should call ToList() on the query so that it pulls back the data then convert the date to the local time zone:
var data = db.Logs.OrderByDescending(l => l.Date)
.Where(l => ((DateTime)l.Date).ToString().Contains(search)
|| l.Name.Contains(search))
.Skip((pageNumber-1)*pageSize).Take(pageSize)
.ToList(); //ToList() causes the query to execute
//now you can convert the Date
foreach (var item in data)
{
item.Date = item.Date.ToLocalTime();
}
return View(data);
You should also use Skip
and Take
in the query instead of ToPagedList
so that you're not pulling back ALL of the data.
4) In your View (not the Controller) you can call ToLocalTime when displaying the variable... (assuming Razor) @Model.Date.ToLocalTime()
You must remember though that ToLocalTime is going to convert the Date to the local time that Your Server is set to, not the local time of the user viewing the web page. If you want to do that then you need to either get their time zone from the request headers or through javascript and pass it with the request, then use that value to format the Date before it's passed back to the View - or just do that conversion client-side using javascript.