Convert DateTimeOffset to DateTime and add offset to this DateTime

淺唱寂寞╮ 提交于 2020-07-05 05:24:16

问题


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"


回答1:


Use DateTimeOffset.UtcDateTime:

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



回答2:


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


来源:https://stackoverflow.com/questions/27959100/convert-datetimeoffset-to-datetime-and-add-offset-to-this-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!