Dynamics CRM 2016 · Dynamics CRM Online

CRM 2016 Online: User Local DateTime issue

Right! CRM DateTime can sometimes cause you a lot of grief. Understanding if it is local time or utc time that is returned helps, but there is a catch with CRM Online!

With the new version of Dynamics CRM, we have more options for DateTime behaviors:
– User Local
– DateOnly
– TimeZone Independent

This post talks about the User Local behavior.

Facts:
– DateTime is saved into SQL db as UTC
– Retrieve DateTime from SDK returns UTC
– DateTime is displayed on CRM as Local
– Update operation treats DateTime as Local (CRM converts to UTC when saving to SQL db)

Therefore, when retrieving DateTime from UTC, we should be aware if we need convert to Local using ToLocalTime().

The catch of using ToLocalTime() is that it relies on the server’s timezone settings. And on CRM Online we cannot rely on the this method because of server location and also we cannot be sure of the timezone of which the server is set (my guess is it is set on GMT).

So a more reliable way to convert UTC to Local is using the TimeZoneBias in UserSettings. The TimeZoneBias is set in minutes relative to GMT as follows.
+1 will have TimeZoneBias -60
GMT will have TimeZoneBias 0
-1 will have TimeZoneBias +60

using (var serviceContext = new XrmServiceContext())
{
    var utcNow = DateTime.UtcNow;

    var timeZoneBiasInMinutes = serviceContext.UserSettingsSet.Single(x => x.SystemUserId == currentUserId).TimeZoneBias;

    var userLocalTime = utcNow.AddMinutes(bias * -1);
}

Cheers,
Sy

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s