How to get UTC equivalent for my local time in C #

My car is on a PDT, and if I say DateTime.Now, I get the local time, which is said to be equivalent to September 18, 2012 at 6:00:00. I want to get the UTC equivalent for this datetime instance. UTC will be 7 hours ahead of PDT and 8 hours ahead of PST. I want to automatically consider daylight saving time.

Any idea on how I can do this?

+4
source share
3 answers

you can use

var now = DateTime.UtcNow; 

To convert an existing DateTime if it has timezone information, you can use DateTime.ToUniversalTime () . If you get an instance of DateTime, for example,

 var localNow = DateTime.Now; // Has timezone info 

he will have time zone information. If you create it, for example. using a tick counter, it will not contain time zone information unless you explicitly provide it.

 var unspecifiedNow = new DateTime(someTickCount); // No timezone info 

It should be noted that the processing of time zones in .NET is not optimal. You can take a look at Noda Time ( Jon Skeet project) if you need to do something with time zones.

+11
source

Use the DateTime method. ToUniversalTime .

+8
source

If you want to convert any date from your time zone to UTC, follow these steps:

 TimeZone.CurrentTimeZone.ToUniversalTime(myLocalDateTime) 

If you want to convert it from UTC:

 TimeZone.CurrentTimeZone.ToLocalTime(myUtcDateTime) 
+4
source

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


All Articles