Search code examples
c#wcfdatetimedynamics-crm

How to convert date according to the timezone/country in C#?


I have created a WCF Rest service for checking and validating license by comparing date. This service uses for Microsoft Dynamics CRM. CRM user can be from any country.

I have faced few issue since few days especially in the conversation of Date and comparing of it.

Service provides this date in "MM/dd/yyyy time" format. i.e 11/4/2027 12:00:00 AM. It is in the string. I want to convert it in DateTime format such a way that it should convert according to current DateTime format.

//C# Current code
string strValidUpToDate = "11/4/2027 12:00:00 AM";
Date validUpToDate = Convert.ToDateTime(11/4/2027 12:00:00 AM);

Above doesn't provide appropriate format if country changed.

Can anybody please guide me?


Solution

  • CRM stores date time in UTC in database tables. CRM user maybe in different countries (timezone) but the system will calculate it based on user settings & store in offset. When the same data is retrieved inside platform, CRM will reverse engineer it & show based on current user settings.

    If the same data is queried in code it will come as it is. ie UTC. You have to take care of timezone conversion in code to get desired results.

    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
    DateTime localDatetime = TimeZoneInfo.ConvertTimeFromUtc(yourUTCDateTime, tz);