DateTime.ToLocalTime
is not supported in Linq to EF.
What's the alternative? I am running out of idea.
DateTime.ToLocalTime
is not supported in Linq to EF.
What's the alternative? I am running out of idea.
Instead of using .ToLocalTime() inside your Linq query, use the opposite conversion outside of the query on the parameters.
var dateUniversal = dateParam.ToUniversalTime();
var query = myTable.Where( t => t.DateTime > dateUniversal );
I used a combination of Extensions plus relying on the value passed from the front-end of my app to be in LocalTime. So, If I had two date times.. like.. a start date and end date parameter for a report, I'd put them up there.. let the user submit in LocalTime.. then on the back end part of my Controller.. I'd use the sdate and edate variables in my Linq to Entities Query. The static extension methods I threw into a static helper class. Sorry that I'm over a year late. : )
DateTime sdate = CalcHelper.AbsoluteStart(model.StartDate);
DateTime edate = CalcHelper.AbsoluteEnd(model.EndDate);
public static DateTime AbsoluteStart(this DateTime dateTime)
{
return dateTime.Date.ToUniversalTime();
}
public static DateTime AbsoluteEnd(this DateTime dateTime)
{
return AbsoluteStart(dateTime).AddDays(1).AddTicks(-1).ToUniversalTime();
}
if you get the timezone offset from the server you might be able to use EntityFunctions to apply the offset in your linq query
var offset = TimeZoneInfo.Local.BaseUtcOffset.TotalMinutes;
var result = db.Dates.Where(a =>
EntityFunctions.DiffDays(EntityFunctions.AddMinutes(a.Date, offset), DateTime.Now) == 0);
You can try like this:
var promotions = _promotionService.GetAll(
x => (DbFunctions.TruncateTime(x.CreatedDate.Value) >= viewModel.GTXFromDate.Date)
&& (DbFunctions.TruncateTime(x.CreatedDate.Value) <= viewModel.GTXToDate.Date));
As a rule, you should store dates and times in UTC in your database.
Convert any local date/times to UTC in your code before you store them in the database.
Similarly, if you need to show local time from the UTC in the database, then convert it in code after the database fetch.
Found the solution on this question
public partial class Person {
partial void OnLoaded() {
this._BirthDate = DateTime.SpecifyKind(this._BirthDate, DateTimeKind.Utc);
}
}
Convert DateTime to String for comparison, for example:
const string DATE_FORMAT = "yyyy/MM/dd";
var query = sampleTable.Where(x => x.DateTime.ToString(DATE_FORMAT) > DateTime.Now.ToString(DATE_FORMAT));