Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core DateTime - ToLocalTime vs ConvertTime

Tags:

c#

.net-core

What is the correct way of converting UTC DateTime to local time (CET)? Should I use System.DateTime.ToLocalTime() or TimeZoneInfo.ConvertTime()? Are there any differences? Or are they just two methods internally calling each other?

like image 847
lss Avatar asked Jul 12 '17 10:07

lss


People also ask

What is DateTime ToLocalTime?

The ToLocalTime method converts a DateTime value from UTC to local time. To convert the time in any designated time zone to local time, use the TimeZoneInfo. ConvertTime method. The value returned by the conversion is a DateTime whose Kind property always returns Local.

How to convert UTC Date time to local Date time c#?

To convert the UTC DateTime to your Local DateTime , you have to use TimeZoneInfo as follows: DateTime startTimeFormate = x. Startdate; // This is utc date time TimeZoneInfo systemTimeZone = TimeZoneInfo. Local; DateTime localDateTime = TimeZoneInfo.


1 Answers

Both methods should work just fine, I don't think either one is more correct than the other.

The most obvious difference in their standard usage is that System.DateTime.ToLocalTime() uses a local timezone provided by the system, while TimeZoneInfo.ConvertTime() uses whatever timezone you give it (e.g. you hardcode CET).

In both cases you should pay attention to the Kind property, which can sometimes ruin your day.

Anyway, you might want to check this question and of course the MSDN documentation of both methods, which sums up their behavior quite well.

like image 197
Michal S Avatar answered Sep 21 '22 10:09

Michal S