Extension method for DateTime in CRM 2016 to get CRM User TimeZone

/// <summary>
/// Extension method for universal date time zone it will need organization service and input
/// </summary>
/// <param name="coordinatedUniversalTime">Coordinated Universal Time</param>
/// <param name="service">organization service</param>
/// <returns>local user date time </returns>
public static DateTime LocalDateTime(this DateTime coordinatedUniversalTime, IOrganizationService service)
{
int timeZoneCode = -1;
var currentUserSettings = service.RetrieveMultiple(
new QueryExpression("usersettings")
{
ColumnSet = new ColumnSet("timezonecode"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression("systemuserid", ConditionOperator.EqualUserId)
}
}
});

if (currentUserSettings.HasRecords())
{
if (currentUserSettings.Entities[0].Attributes["timezonecode"] != null)
{
timeZoneCode = (int)currentUserSettings.Entities[0].Attributes["timezonecode"];
}

var request = new LocalTimeFromUtcTimeRequest
{
TimeZoneCode = timeZoneCode,
UtcTime = coordinatedUniversalTime.ToUniversalTime()
};

var response = (LocalTimeFromUtcTimeResponse)service.Execute(request);
return response.LocalTime;
}

return coordinatedUniversalTime;
}
}

————————--How to use this-—————————

DateTime.UtcNow.LocalDateTime(this.OrgService)

in need you can use

string.Format(CultureInfo.CurrentCulture, “{0:yyy MM dd}”, DateTime.UtcNow.LocalDateTime(this.OrgService)

Advertisements

One thought on “Extension method for DateTime in CRM 2016 to get CRM User TimeZone

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s