Date Issue

linq

In MS CRM, we have multiple date time zone setting, each user can set his own time zone as per his requirement.

Thus, Microsoft Dynamics CRM stores all DateTime fields in UTC time, so by using the ‘DateTime.UtcNow’ approach our dates will be converted into UTC time before hitting the database.

For example, default time is 12:00:00, in database it will be stored as 11:00:00. That is why developer will get 11PM in plugin. When our users read the date through CRM it will be converted back into their local time zone and user will read correctly time.

To handle this kind of situation we needs to retrieve users personal time zone from his personal setting and convert his date as per that time zone.

Here is the sample code for this….

/// <summary>
 /// convert date as per user setting 
 /// </summary>
 /// <param name="utcTime"></param>
 /// <param name="service"></param>
 /// <returns></returns>
 private DateTime RetrieveLocalTimeFromUTCTime(DateTime utcTime, IOrganizationService service)
 {
 int? timeZoneCode = RetrieveCurrentUsersSettings(service);

 if (!timeZoneCode.HasValue)
 throw new Exception("Can't find time zone code");

 var request = new LocalTimeFromUtcTimeRequest
 {
 TimeZoneCode = timeZoneCode.Value,
 UtcTime = utcTime.ToUniversalTime()
 };

 var response = (LocalTimeFromUtcTimeResponse)service.Execute(request);

 return response.LocalTime;
 //var utcTime = utcTime.ToString("MM/dd/yyyy HH:mm:ss");
 //var localDateOnly = response.LocalTime.ToString("dd-MM-yyyy");
 }

 /// <summary>
 /// get time zone-code from user settings
 /// </summary>
 /// <param name="service"></param>
 /// <returns></returns>
 private int? RetrieveCurrentUsersSettings(IOrganizationService service)
 {
 var currentUserSettings = service.RetrieveMultiple(
 new QueryExpression("usersettings")
 {
 ColumnSet = new ColumnSet("localeid", "timezonecode"),
 Criteria = new FilterExpression
 {
 Conditions =
 {
 new ConditionExpression("systemuserid", ConditionOperator.EqualUserId)
 }
 }
 }).Entities[0].ToEntity<Entity>();

 return (int?)currentUserSettings.Attributes["timezonecode"];
 }

Reference: Retrieve time zone information

Thanks …..

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