Friday, September 9, 2011

Creating Entities with dates in MS CRM 2011

MS CRM stores date values internally in UTC date format, so when I was programmatically creating appointments earlier this week I was getting weird date issues.

The solution is really simple



I figured out the following method for setting the dates in the entities. Basically you grab the difference between the current local DateTime, and the current UTC DateTime like this:


Code Snippet
  1. TimeSpan utcOffset = DateTime.Now - DateTime.UtcNow;


Then when you create the entity just add the utcOffset to any date values.


Code Snippet
  1. //    figure out the offset between now and UTC time, so that we can store the dates as UTC dates.
  2. TimeSpan utcOffset = DateTime.Now - DateTime.UtcNow;
  3.  
  4. Appointment apt = new Appointment()
  5. {
  6.     dwe_AppointmentType = appointmentType,
  7.     Subject = account.Name,
  8.     IsAllDayEvent = true,
  9.     ScheduledStart = aptDate + utcOffset,
  10.     ScheduledEnd = aptDate.AddDays(1) + utcOffset,
  11.     dwe_country = account.dwe_CountryId,
  12.     RegardingObjectId = new EntityReference()
  13.         {    
  14.             Id = account.AccountId,
  15.             LogicalName = "account"
  16.         },
  17.     OwnerId = account.OwnerId,
  18. };


and it's as simple as that.

No comments:

Post a Comment