Convert a time to specified time zone using C#?

2019-02-19 09:54发布

I'm working on an application in C# with .Net 3.5. I have time zone value of the User is stored in DB with this format (-05:00,1), where -5.00 represents EST time zone value and the 1 indicates that this time zone follows daylight saving (if 0 not a daylight saving zone).

Now I want to convert any date time value into this timezone value considering the daylight saving value.

Any help is appreciated. Thanks

4条回答
可以哭但决不认输i
2楼-- · 2019-02-19 10:29

@skeet is right about the timezones. Trust me they are crazy. You have places like India that are .5 hour off. Places like Venezuela that just up and change their timezone. Places like the US that change the date their DST starts and ends on. You have to remember that timezones are subject to the political will of the country, and they do change (more often than you would think). Use the Timezone id instead of trying to track the offset in your DB.

And if you haven't figured it out already, using DateTimeOffset will make your life 100x easier if you have to deal with Timezones.

查看更多
甜甜的少女心
3楼-- · 2019-02-19 10:41

Use DateTime.ParseExact() for this. But this doesn't support the DST indicator.

查看更多
Rolldiameter
4楼-- · 2019-02-19 10:46

Why don't you get the GMT0 and add user's delay (+/-) ?

查看更多
萌系小妹纸
5楼-- · 2019-02-19 10:47

Having just an offset and whether or not it's in daylight saving time isn't really enough to indicate a time zone: there can be several time zones with the same standard offset and DST offset, but which have DST transitions at different times.

Is this data already in the database, or are you still designing it? Ideally you should store a time zone ID - the ones TimeZoneInfo works with are Windows IDs, which isn't ideal IMO (I prefer the IANA/Olson IDs that the rest of the industry tends to work with) but at least it does represent a real time zone.

Once you've got a TimeZoneInfo and an instant that you want to convert, ConvertTimeFromUtc and ConvertTimeToUtc are probably what you're after - but be careful about what you mean by "any date time value"; you need to make sure you always know exactly what you're representing.

The BCL is somewhat woolly on all of this, which is one of the reasons I started Noda Time, which allows use of the IANA time zone data as well as the BCL.

查看更多
登录 后发表回答