65

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"

spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Alex
  • 8,908
  • 28
  • 103
  • 157
  • 1
    That would be odd. Something like `1/15/2015 17:37:00 -05:00` normally means "The local time is 17:37, but that's 5 hours behind UTC" - in other words, a result of `1/15/2015 22:37:00` would be useful, as that's the UTC time - but 12:37 would be applying the offset *twice*. Can you explain more about your context? – Jon Skeet Jan 15 '15 at 08:15
  • 1
    @JonSkeet oops,I do wrong, I want to be "1/15/2015 22:37:00" – Alex Jan 15 '15 at 08:20
  • you can use , DateTimeOffset.DateTime property, ref: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.datetime?view=net-5.0. – SaddamBinSyed Feb 03 '21 at 06:05

3 Answers3

150

Use DateTimeOffset.UtcDateTime:

DateTime utc = myDTO.UtcDateTime; // 01/15/2015 22:37:00
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
11

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
RvdV79
  • 2,002
  • 16
  • 36
0

There is new Property in DateTimeOffset in new version of .net, use it:

DateTimeOffset.LocalDateTime
PurTahan
  • 789
  • 8
  • 24