Set Date Time Field to Now in Plugin Dynamics CRM 2011

In Dynamics CRM 2011 when you are creating or updating records through a plugin, you will sometimes be required to set a date field to the current date and time of the plugins execution.
There are two ways of doing this with a plugin. One method is using DateTime.Now, which will give you the local time of the CRM Server. The other method (the recommended method) is using DateTime.UtcNow. This will give you the CRM Server time, but it will be converted into UTC time.
 Set Date Time Field to Now in Plugin Dynamics CRM 2011
Dynamics CRM 2011 stores all Date/Time fields in UTC time, so by using the ‘DateTime.UtcNow’ approach our dates will be converted into UTC time before hitting the database. When our users read the date through CRM it will be converted back into their local time zone, and will read correctly for them.
If we check the database, we can see how the date from the image above is actually stored in the database using UTC time:
 Set Date Time Field to Now in Plugin Dynamics CRM 2011
If you were to set a date using ‘DateTime.Now’, the exact server time would be saved into the database with no conversion to ‘UTC’ time first. When the user reads the date in CRM it would then be converted into their local time, and will read incorrectly for them.
I’ve created a scenario to better describe how this works. One using each method:
Using DateTime.Now:
Your CRM Servers time zone is UTC+13:00. You trigger a plugin on 7/03/12 at 3:00pm which creates a Task. The Tasks Due Date is set using DateTime.Now. The Due Date stored in the Database is 7/03/12, 3:00pm (the exact server time). When you open the Task, the Due Date reads incorrectly as 8/03/12, 4:00am.
Using DateTime.UtcNow:Your CRM Servers time zone is UTC+13:00. You trigger a plugin on 7/03/12 at 3:00pm which creates a Task. The Tasks Due Date is set using DateTime.UtcNow. The Due Date stored in the Database is 7/03/12, 2:00am (UTC time). When you open the Task, the Due Date reads correctly as 7/03/12, 3:00pm.
Here is an example of how you should set your date fields in your plugins using DateTime.UtcNow:
        Entity task = new Entity("task"); 
        task["scheduledend"] = DateTime.UtcNow;
        task["subject"] = "Lottery Ticket!"
        sdk.Create(task);

In some cases it might make sense to use DateTime.Now as appose to DateTime.UtcNow, for example if you are comparing a date with the current date, and you want it to use the local time rather than the UTC time. Whenever you are setting the value of Date/Time fields though, you should always use the UTC time rather than the CRM Server local time.       

Comments

Popular posts from this blog

Workflow Activity Input and Output Parameters and Data Types in MS CRM 2013/15/16

Get Workflow Guid in Javascript using OData query

Convert Plugin to Sandbox mode,