There is a difference between local and server time

Jeyhun Rahimov picture Jeyhun Rahimov · Mar 20, 2013 · Viewed 15.6k times · Source

In MVC4 C# application I used DateTime.Now when object created in my application. After deploying, there was +8 hours difference between local computer and hosting. Then I changed it to DateTime.UtcNow, now difference is -4 hours.

For example in my computer date is 20 Mar 2013, 14:28:12, but date stores to database like 20 Mar 2013, 10:28:12.

What should I do all user in all countries to use 1 same date?

Edit: my time zone is (UTC+04:00) Baku, server is following PST

Answer

Richard Hooper picture Richard Hooper · Mar 20, 2013

Let say for example that your user is in New York (GMT - 5) and your server is in India (GMT + 5:30).

When the user sees a "local" time of 10:00am (EST), your server would see a "local" time of 7:30pm (IST). However, by using UTC in both places....the user would see a UTC time of 3pm and the server would see a UTC time of 3pm.

Using UTC in all places but keeping a referece of the users time zone allows you to always be working in UTC but still convert the times into the users "local" time when you want to show it to them.

You also cannot rely on where a server is hosted especically if it is a virtual server. Nor can you assume what time zone the hosting company set their servers to. Best to always code defensivly by using DateTime.UtcNow when storing date times in the database.

To convert this UTC time back to the time zone of a user you will need to do the following:

DateTime utcTime = new DateTime(2013, 03, 25, 10, 20, 00);
TimeZoneInfo usersTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime usersLocalTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, usersTimeZone);
Console.WriteLine(utcTime.ToString("hh:mm:ss");
Console.WriteLine(usersLocalTime.ToString("hh:mm:ss");

FYI, you can find a list of the timezones from:

TimeZoneInfo.GetSystemTimeZones()

This should print out:

10:20:00
05:20:00

As you can see, you will need to know the users time zone. There are 2 ways to know the users time:

  1. Have the user select their timezone in their user preferences
  2. Use some javascript to detect the timezone of their machine and post it back with the form

I would suggest the first option there as the second one can make things more difficult for people. For example, if they are UK based and fly to the states for the week. Everything will change zones and they may not realise!