Convert DateTimeOffset to DateTime and add offset to this DateTime

C#DatetimeDatetimeoffset

C# Problem Overview


I have 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 convert to DateTime and add this offset "-0500" in the resulted DateTime

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

C# Solutions


Solution 1 - C#

Use DateTimeOffset.UtcDateTime:

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

Solution 2 - C#

You do not have to add the offset to the time when using UTC time. According to your example, you are referring to the UTC time. So this would mean that you can use DateTimeOffset.UtcDateTime like I demonstrated 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - C#Tim SchmelterView Answer on Stackoverflow
Solution 2 - C#RvdV79View Answer on Stackoverflow