0

I'm working on a project which is in MVC which have some pages displaying datetime values as per the time zone it was inserted in the database. Now my requirement is to display it as per the time zone in which the admin or the user is loggged in. What can be the best possible way to achieve that.

I want to to it on the front end, as i cannot update it on the backend.

I have a userinfo table which have a time_zone_id mapping column to another table i.e time_zone in which time zone is defined for registered users.

Instead of going to every controller and changing the date time fields(adding or substracting the time zone), is there any other way to achieve the same?

Let me know if the question is not cleared.

Orace
  • 7,822
  • 30
  • 45
rohit singh
  • 550
  • 1
  • 11
  • 32

1 Answers1

0

There is no built-in way to apply time zone changes globally in a .NET application. It would be dangerous if it was such a mechanism, as different parts of an application may need to work with time zones other than just the one assigned to a specific user.

However, you have bigger problems to solve. You stated in comments that your time zones are stored as a numerical value, time_in_minutes. That only will represent a time zone offset, not an actual time zone.

There is a significant difference between an offset and a time zone. Any solution that only tracks an offset will not be able to properly convert times around the world, primarily due to daylight saving time. See "Time Zone != Offset" in the timezone tag wiki and the graphs in the dst tag wiki.

Also, you implied that the times store in the database were in the local time of the time zone referenced by the time zone id. That is also a problem, as you could be storing ambiguous values during the fall-back DST transition.

You should instead be doing the folowing:

  • Store your values either in UTC or in a datetimeoffset data type. (See DateTime vs DateTimeOffset if you're not sure which to use.)

  • In your time zone table, you should store a string containing a time zone identifier. You can choose between Windows time zones or IANA time zones.

    • For Windows time zones, the identifiers contain values like "Eastern Standard Time", even when they actually represent the full US Eastern Time zone, including EST and EDT (don't get caught up in the naming discrepancies). If you use these, then you would use the TimeZoneInfo class in your .NET code to do the conversions.

    • For IANA time zones, the identifiers are more sensible, such as "America/New_York", or "Asia/Tokyo". You can find a list of them here. In .NET, they easiest way to work with these is with the Noda Time library. Given the choice, this would be my recommendation.

You should read through the timezone and dst wiki's thoroughly. I'll also recommend the following videos:

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575