Using TimeZones on website using ASP.Net 3.5 / SQL

2020-07-27 19:21发布

问题:

I am trying to determine, how I should implement local time in a web-app. All users are logged in, there are no anonymous users. They will need to see all time-values in their local time.

Is this how it should be done?

  1. All DateTime values are saved as UTC-time in database
  2. Each user has a UTC-Offset value stored in his profile
  3. When displaying a datetime-value, I take the value from the database, and apply the users offset.

Is this the way to go? Or am I missing something?

回答1:

Don't store a UTC offset for the user - that's not enough to know the full time zone information. You should store their Olson time zone ID, e.g. "Europe/London". Then you can display any UTC time in the local time, taking into account historical changes, daylight savings etc.

EDIT: It looks like the TimeZoneInfo ID isn't actually in the normal Olson format - but so long as there's something sensible you can display to the user (as a choice), and an ID you can retrieve the zone from later on, that's probably okay... you may have difficulties if you need to interoperate with other systems later though.

You should ask the user for their time zone (possibly trying to guess it first through JavaScript) - they will have more information than you do.

You should investigate the TimeZoneInfo class for more on this - I can't say I've used it much myself, but it's the way to go as of .NET 3.5. In particular, FindSystemTimeZoneById and GetSystemTimeZones will be important.

Time zones are a pain in general, but at least TimeZoneInfo gives a lot more support than the old TimeZone type.



回答2:

That sounds like the most straightforward way to me. The only slip ups I could see occurring are some areas (such as parts of Indiana and I think all of Arizona) don't cooperate with daylight savings time, so you'll have to take extra precautions displaying the correct time for them.