Converting DateTimeOffset to DateTime and adding an offset to this DateTime

I have a DateTimeOffset :

DateTimeOffset myDTO = DateTimeOffset.ParseExact( "2015/01/15 17:37:00 -0500", "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture); Console.WriteLine(myDTO); 

// result => "1/15/2015 17:37:00 -05: 00"

How to convert to DateTime and add this offset "- 0500" to the given DateTime

// desired result => " 1/15/2015 22:37:00 "

+5
source share
2 answers

Use DateTimeOffset.UtcDateTime :

 DateTime utc = myDTO.UtcDateTime; // 01/15/2015 22:37:00 
+11
source

You do not need to add an offset at time UTC. According to your example, you mean UTC time. This means that you can use DateTimeOffset.UtcDateTime , as I showed here:

 DateTimeOffset myDTO = DateTimeOffset.ParseExact( "2015/01/15 17:37:00 -0500", "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture); Console.WriteLine(myDTO); //Will print 1/15/2015 17:37:00 -5:00 //Expected result would need to be 1/15/2015 22:37:00 (Which is UTC time) DateTime utc = myDTO.UtcDateTime; //Yields another DateTime without the offset. Console.WriteLine(utc); //Will print 1/15/2015 22:37:00 like asked 
+4
source

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


All Articles