Convert Dynamics CRM 2011 DateTime to Server Local Time in a Plugin

Paul Nieuwelaar, 11 May 2012

In a previous post, I talked about setting Date/Time fields in plugins, and how Dynamics CRM 2011 stores all date fields as UTC time in the database. This means when setting dates to the current time, we must get the current UTC time instead of the Users or Servers Local Time.

When we are retrieving dates through a plugin, we are faced with the same problem. Because the dates are stored as UTC, when we retrieve the date value we get the UTC time. If we are doing comparisons against this date, or displaying it somewhere it will be incorrect.
 Convert Dynamics CRM 2011 DateTime to Server Local Time in a Plugin

In the example above we’re taking the Estimated Close Date from the Opportunity and setting it into the Topic using a plugin. As you can see, the Date and Time in the Topic appears differently to the actual Estimated Close Date. This is because we are getting the fields UTC time, and setting that directly into the Topic. The Estimated Close Date is converted to our Local Time when viewing it on the form, which is why the value retrieved in the plugin is different.

To get the retrieved DateTime into our Servers Local Time, all we need to do is add ‘ToLocalTime()’ onto the end of our date variable. This will take the UTC time from the database, and convert it into the Server Local Time, so that when you are displaying the date value it is the same as the date on the form.

NOTE: This works best with CRM On-Premise, across one Country/Time Zone.

Here’s an example of converting the date into the Servers Local Time:

DateTime estCloseDate = (DateTime)target.Attributes["estimatedclosedate"];
DateTime estCloseDateLocal = estCloseDate.ToLocalTime();
 Convert Dynamics CRM 2011 DateTime to Server Local Time in a Plugin

You can see here when we add ToLocalTime() onto our UTC date, it appears the same as the actual date we see when reading the form, because our Server Time is the same as our Users Time.

If you are retrieving a Date field, and then setting the value into another Date field, then you should not convert to Local Time. In that case you would be getting a UTC date, and then setting a UTC date so no conversion is needed in between. As long as you remember to set dates in UTC time, and display them in Local Time you should be alright.