TimeZoneInfo.ConvertTimeFromUtc c#

 ̄綄美尐妖づ 提交于 2021-01-29 03:26:26

问题


var Result1 = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local)

var Result2 = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,  TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id));

Both this convert Utc time to local time, is there any difference between this 2 different ways in result or performance?

which is good?

why Microsoft not using TimeZoneInfo.Local directly(as for Result1) in sample here


回答1:


The only difference is that the second takes a detour by getting a TimeZoneInfo object, getting the id for it, and looking up the same object again using the id.

The reason that the code in the example is using the FindSystemTimeZoneById method is that it's getting the TimeZoneInfo object for a known id, it's not getting that id from a TimeZoneInfo object that it already has.




回答2:


I think it might be worth while to extend my comment into an answer.

I have an application in which the "local" time zone is configured in the DB, it has nothing to do with the local time zone of the server itself. (It is running in a cloud server). So, using TimeZoneInfo.Local is not good for me.

What I would like to do is to read from the DB what time zone should be used, and then convert the time from UTC to that time zone. Hence I'm using:

TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,  TimeZoneInfo.FindSystemTimeZoneById(GetTimeZoneId()));

Where GetTimeZoneId() reads from the DB.




回答3:


It's a matter of how you're gonna use them. TimeZoneInfo.FindSystemTimeZoneById() is used when you want a different timezone other than your local. If you're always going to use your local timezone, just use TimeZoneInfo.Local.

In terms of performance, I don't think there is much difference. However, you can try to profile it using .NET Profiler or other profilers to see how much difference does the two have.




回答4:


Yes, there is a difference between those two invocations.

Windows has a feature to adjust for DST automatically, which can be seen in two places on modern Windows:

In the Date & Time settings page:

In the Date & Time control panel under Time Zone Settings:

This setting is recommended to remain ON in most cases. If however you turn it off, TimeZoneInfo.Local will take that into account.

If you call TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id), the result will be the same as if the setting were on, even if it is actually turned off. This is by design.



来源:https://stackoverflow.com/questions/16809007/timezoneinfo-converttimefromutc-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!