Convert datetime to user local in D365 Plugins
- Get link
- X
- Other Apps
Background:
There could be times where we need to compare the datetime field with today's date in the plugin for some validations.
Example:
We had a requirement to compare the expiry date field with today's date.
During comparison it was not giving the expected result. In our scenario, User's timezone is in IST. In plugin, the expiry date was returned in UTC. So, if user sets the date set as 21-Oct-2021 12:00:00 PM IST, in plugin code it was returning 19-Oct-2021 12:00:00 IST and comparing with the today's date, 21-Oct-2021 12:00:00. This resulted in incorrect comparison.
So, we had to convert both expiry date and today's date to user local before comparison.
Following are the steps to achieve the same.
1. Get the initiating user id in plugin
2. Retrieve timezonecode from user settings entity based on initiating user id.
3. Initiate LocalTimeFromUtcTimeRequest by passing expiry date in UTC along with user's timezonecode to get the User's local time.
Below is the sample code snippet.
public DateTime GetUserLocalTime(DateTime dateValue)
{
// Retrieve Current User Settings.
QueryExpression querycurrentUserSettings = new QueryExpression
{
EntityName = "usersettings",
ColumnSet = new ColumnSet("timezonecode"),
Criteria =
{
Filters =
{
new FilterExpression
{
Conditions =
{
new ConditionExpression("systemuserid", ConditionOperator.Equal, pluginContext.InitiatingUserId)
}
}
}
},
NoLock = true,
};
EntityCollection userSettingsCollection = service.RetrieveMultiple(querycurrentUserSettings);
int timeZoneCode = 0;
if (userSettingsCollection != null)
{
if (userSettingsCollection.Entities.Count > 0)
{
// Get User's Timezone code
Entity record = userSettingsCollection[0].ToEntity<Entity>();
timeZoneCode = (int)record.Attributes["timezonecode"];
}
}
// Create LocalTimeFromUtcTimeRequest
LocalTimeFromUtcTimeRequest request = new LocalTimeFromUtcTimeRequest
{
TimeZoneCode = timeZoneCode.Value,
UtcTime = dateValue.ToUniversalTime()
};
LocalTimeFromUtcTimeResponse response = (LocalTimeFromUtcTimeResponse)service.Execute(request);
// Return the local time
return response.LocalTime;
}
Now you can pass the date value to GetUserLocalTime to get the user local timezone.
- Get link
- X
- Other Apps
Comments
Post a Comment