How can I convert a UTC date to my time zone?

I need to convert the time to "UTC + 03: 30 Time Zone" in my web application here: UTC date:

DateTime dt = DateTime.UtcNow; 

Is there any function to convert UTC to my timezone or not? I do not want to involve myself in writing a new function in my application if there is a function in ASP.NET.

The application can be hosted on different servers in the world, which is why I used the UTC date.

I need a function to add 3:30 to the current UTC time.

+4
source share
2 answers

Are you sure your time zone is really UTC +3:30, all the time, without daylight saving time? If so, you can create a DateTimeOffset with an appropriate offset (3.5 hours). For instance:

 DateTimeOffset dtOffset = new DateTimeOffset(DateTime.UtcNow, TimeSpan.FromHours(3.5)); 

Of course, this gives you a DateTimeOffset instead of a DateTime ... can you use this?

The best solution is to use TimeZoneInfo - for example, you can get the correct time zone and call

 DateTime local = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tzInfo); 

... or you can use TimeZoneInfo , but still get DateTimeOffset :

 DateTimeOffset dto = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzInfo); 

Personally, I would recommend using DateTimeOffset if you can, as the DateTime value is somewhat ambiguous and hardly works correctly.

The .NET processing date and time is a bit of a mess, unfortunately :( I have a project called Noda Time that should improve if we ever finish it, but it's not ready for production yet.

+7
source

this will allow you to convert UTC to any time zone

 Shared Function FromUTC(ByVal d As Date, ByVal tz As String) As Date Return (TimeZoneInfo.ConvertTimeBySystemTimeZoneId(d, TimeZoneInfo.Utc.Id, tz)) end function 

you can get a list of time zones using

 For Each timeZone As TimeZoneInfo In tzCollection Console.WriteLine(" {0}: {1}", timeZone.Id, timeZone.DisplayName) Next 
-1
source

Source: https://habr.com/ru/post/1342954/


All Articles