Friday, April 26, 2013

Get User Local Time From UTC Time in MSCRM 2011

The following piece of code will return user's local time from utc time , the user time zone will be retrieved by another function which I have posted in another of my blogs , iam pasting the code here also for making it easy to understand
 
 
 

        private DateTime GetUserLocalTimeFromUTCTime(IOrganizationService service, DateTime utcDate, Guid userId)

        {

            Entity loggedInUser = null;

            int timeZoneCode = 0;

            DateTime returnDateTime = DateTime.UtcNow;

            try

            {

                loggedInUser = GetUserTimeZone(service, userId);

                if (loggedInUser != null && loggedInUser.Attributes.Contains("timezonecode"))

                {

                    timeZoneCode = ((int)loggedInUser.Attributes["timezonecode"]);

                }

                LocalTimeFromUtcTimeRequest request = new LocalTimeFromUtcTimeRequest();

                request.UtcTime = utcDate;

                request.TimeZoneCode = timeZoneCode;

                LocalTimeFromUtcTimeResponse response = (LocalTimeFromUtcTimeResponse)service.Execute(request);

                returnDateTime = response.LocalTime;

                return returnDateTime;

            }

            catch (FaultException<OrganizationServiceFault>)

            {

                //return UtcNow when the corresponding userId doesn't have any local time zone settings (for example "Network Service")

                //throw;

                return returnDateTime;

            }

            catch (Exception)

            {

                //return UtcNow when the corresponding userId doesn't have any local time zone settings (for example "Network Service")

                //throw;

                return returnDateTime;

            }

        }

 
 
 
 
        private Entity GetUserTimeZone(IOrganizationService service, Guid userId)
        {
            try
            {
 
                RetrieveUserSettingsSystemUserRequest request = new RetrieveUserSettingsSystemUserRequest();
                request.ColumnSet = new ColumnSet("timezonecode");
                request.EntityId = userId;
                RetrieveUserSettingsSystemUserResponse response = (RetrieveUserSettingsSystemUserResponse)service.Execute(request);
                return response.Entity;
            }
            catch (FaultException<OrganizationServiceFault>)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
 
 

     

No comments: