Kuttan Sujith
Kuttan Sujith

Reputation: 7979

TimeZoneInfo.ConvertTimeFromUtc c#

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

Upvotes: 2

Views: 4333

Answers (4)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

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: screenshot

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

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.

Upvotes: 0

Guffa
Guffa

Reputation: 700152

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.

Upvotes: 1

aiapatag
aiapatag

Reputation: 3430

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.

Upvotes: 0

omer schleifer
omer schleifer

Reputation: 3935

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.

Upvotes: 0

Related Questions