CRM Handling UTC DateTimes to LocalTimes
private void CreateMissingEditions(IOrganizationService service, EntityReference newspaper, EntityReference newspaperPage, List<DateTime> dates, Guid userId, out int success, out int count)
{
success = 0;
count = 0;
if (dates == null || dates.Count == 0 || (newspaper == null && newspaperPage == null))
return;
//GET User Time Zone
var timeZone = GetUserTimeZone(service, userId);
var existingEditions = GetExistingEditions(service, newspaper, newspaperPage, dates.Min(d => d), dates.Max(d => d));
//Convert UTC Dates retrieved by fetchxml to LocalTime
var existingEditionDates = existingEditions.Select(e => TimeZoneInfo.ConvertTime(e.GetAttributeValue<DateTime>("ad_date"), timeZone).Date).ToList();
foreach (var date in dates)
{
if (!existingEditionDates.Contains(date.Date))
{
CreateEdition(service, newspaper, newspaperPage, date);
success++;
}
count++;
}
}
private TimeZoneInfo GetUserTimeZone(IOrganizationService service, Guid userId)
{
int timeZoneCode = 95; //default timezone to (GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague; 95
var userSettings = service.Retrieve("usersettings", userId, new ColumnSet("timezonecode"));
if ((userSettings != null) && (userSettings.GetAttributeValue<int?>("timezonecode") != null))
{
timeZoneCode = userSettings.GetAttributeValue<int?>("timezonecode").Value;
}
return GetTimeZone(service, timeZoneCode);
}
private TimeZoneInfo GetTimeZone(IOrganizationService service, int crmTimeZoneCode)
{
var qe = new QueryExpression("timezonedefinition");
qe.ColumnSet = new ColumnSet("standardname");
qe.Criteria.AddCondition("timezonecode", ConditionOperator.Equal, crmTimeZoneCode);
return TimeZoneInfo.FindSystemTimeZoneById(service.RetrieveMultiple(qe).Entities.First().GetAttributeValue<string>("standardname"));
}