Convert Date from UTC to Time Zone of User

The Date/Time fields stored in CRM with the UTC format, and the Time Zone Code associated with each User in the system settings.
To get the Date/Time field from CRM with the Time Zone of specific user, we must pass the Guid of the user as parameter to get the TimeZoneInfo.


public static DateTime ConvertTimeFromUtc(OrganizationService service, Guid userid, DateTime dateToconvert)
{
//replace userid with id of user
Entity userSettings = service.Retrieve("usersettings", userid, new ColumnSet("timezonecode"));
//timezonecode for UTC is 85
int timeZoneCode = 85;
//retrieving timezonecode from usersetting
if ((userSettings != null) && (userSettings["timezonecode"] != null))
{
timeZoneCode = (int)userSettings["timezonecode"];
}
//retrieving standard name
var qe = new QueryExpression("timezonedefinition");
qe.ColumnSet = new ColumnSet("standardname");
qe.Criteria.AddCondition("timezonecode", ConditionOperator.Equal, timeZoneCode);
EntityCollection TimeZoneDef = service.RetrieveMultiple(qe);
TimeZoneInfo userTimeZone = null;
if (TimeZoneDef.Entities.Count == 1)
{
String timezonename = TimeZoneDef.Entities[0]["standardname"].ToString();
userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timezonename);
}
//converting date from UTC to user time zone
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(dateToconvert, userTimeZone);
return cstTime;
}

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s