Search code examples
c#datetimetimezoneglobalizationutc

Converting DateTime to local not working


In MVC4 C# application I tried convert server time to local time. It works in local, but it does not working when site deploying. For testing I checked some code results in deployed site. They are:

25.03.2013 04:39:31 - DateTime.Now 
25.03.2013 09:39:31 - DateTime.UtcNow
25.03.2013 04:39:31 - DateTime.UtcNow.ToLocalTime()
25.03.2013 09:39:31 - SpecifyKind(DateTime.UtcNow, DateTimeKind.Local)
25.03.2013 04:39:31 - TimeZoneInfo.ConvertTimeFromUtc(DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc), TimeZoneInfo.Local)
25.03.2013 04:39:31 - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, TimeZoneInfo.Local.Id)
25.03.2013 04:39:31 - TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local) 
25.03.2013 04:39:31 - TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local)
25.03.2013 09:39:31 - TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Utc)
Utc - DateTime.UtcNow.Kind

At the same time in my computer time is:

25.03.2013 13:39:31;

I thought it depends on globalization. in config file I tried following variants separately:

    <globalization  uiCulture="en-US"/>,

    <globalization culture="az" uiCulture="az" />,

    <globalization culture="auto" uiCulture="auto" />,

    <globalization culture="az-Latn-AZ" uiCulture="az-Latn-AZ" />,

    <globalization culture="en-US" uiCulture="en-US"/>

But, nothing changed. My local time zone is (UTC+04:00) Baku and I used DateTime.UtcNow in my all codes. Can anybody help me to convert server time and display like local time?


Solution

  • The problem is your site is using the time and timezone of the server where it is located. The solution of your problem is either you change the datetime of the server ( in case you have the rights to do so ) to you local time as on your local machine .

    In case you want the solution using the code you have to use the Timezone to convert UTC time to your specific timezone time . This link will help you : http://msdn.microsoft.com/en-us/library/bb397769.aspx