Server-side Fetchxml returns different results

一世执手 提交于 2019-11-29 16:18:46
Daryl

When working with dates, always remember to convert to utc since that is how CRM stores them in the database.

The native CRM Advanced find is going to look at whatever the current user's time zone is, and convert that whatever time they enter into the advanced find to UTC before performing a SQL query. Your plugin control will need to do the same thing. These are the steps you'll need to perform before putting the criteria in the Fetch Xml / Linq Expression / Query Expression.

  1. Get the user's UserSetting.TimeZoneCode via their SystemUserId.
  2. Lookup the TimeZoneDefinition.StandardName for the TimeZoneCode from step 1
  3. Call TimeZoneInfo.FindSystemTimeZoneById() passing in the Standard Name from step 2 (you can combine steps 1 and 2 into a single query, but I prefer to cache the results of step three using the input from step 1 for a slight performance improvement. ie. use a dictionary with the TimeZoneCode as the key and the TimeZoneInfo as the value)
  4. Use this function to get the UTC value for the time that you're going to use in your plugin query:

public static DateTime ConvertTimeToUTC(DateTime time, TimeZoneInfo timeZone)
{
    if (time.Kind != DateTimeKind.Unspecified)
    {
        // If the DateTime is created with a specific time zone(ie DateTime.Now), getting the offset will
        // blow chow if it isn't the correct time zone:
        // The UTC Offset of the local dateTime parameter does not match the offset argument.
        //Parameter name: offset

        // This quick check will recreate the serverLocal time as unspecified

        time = new DateTime(
            time.Year,
            time.Month,
            time.Day,
            time.Hour,
            time.Minute,
            time.Second,
            time.Millisecond);

    }
    var offest = new DateTimeOffset(time, timeZone.GetUtcOffset(time));
    return offest.UtcDateTime;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!