Strange time zone propagation in the filter
cts-tradeit opened this issue · comments
Current
Sample GET url http://localhost:51994/time-tracks?$filter=((dateFrom+eq+2024-04-17T09:45:00%2B02:00))&$orderby=dateFrom+desc&$skip=0&$top=25 contains time 2024-04-17T9:45:00.0000000+02:00
Produces SQL query that contains "2024-04-17T11:45:00.0000000+02:00". So it get's treated as if the date in the filter was UTC time.
The fault is in fact caused by DateTime being parsed as Kind.Unspecified (where expression in the query contains DateTime of this kind).
Expected
When oDataOptions.TimeZone is set in the configuration of the DateTime will be of Kind.Local and if the timezone in the filter is not the same as specified in TimeZone, the time will be shifted.
This would lead to result query with "2024-04-17T09:45:00.0000000+02:00".
Related to #378
Great solution would be to be able to specify custom deserializer for DateTime, or more precisely converter from DateTimeOffset to DateTime.
It is difficult to understand why such a serious and fundamental problem has not been taken seriously.
Though I don't really want to use the hacky method, it is the only way to fix the bug at present.
public static void HackDateTimeConvert()
{
var targetType = AccessTools.TypeByName("Microsoft.AspNetCore.OData.Edm.EdmPrimitiveHelper");
var targetMethod = AccessTools.Method(targetType, "ConvertPrimitiveValue", new Type[] { typeof(object), typeof(Type), typeof(TimeZoneInfo) });
var prefix = new HarmonyMethod(typeof(ODataEdmStore).GetMethod("HackDateTimeConvertPrefix"));
var harmony = new Harmony("Microsoft.AspNetCore.OData.Edm.Patch");
harmony.Patch(targetMethod, prefix);
}
public static bool HackDateTimeConvertPrefix(ref object __result, object value, Type type, TimeZoneInfo timeZoneInfo)
{
if (value.GetType() == type || value.GetType() == Nullable.GetUnderlyingType(type))
{
__result = value;
return false;
}
if (type.IsInstanceOfType(value))
{
__result = value;
return false;
}
if (type == typeof(DateTime))
{
if (value is DateTimeOffset)
{
DateTimeOffset dateTimeOffsetValue = (DateTimeOffset)value;
TimeZoneInfo timeZone = timeZoneInfo ?? TimeZoneInfo.Local;
dateTimeOffsetValue = TimeZoneInfo.ConvertTime(dateTimeOffsetValue, timeZone);
__result = dateTimeOffsetValue.UtcDateTime;
return false;
}
}
return true;
}