C# 将DateTimeOffset转换为DateTime并将偏移量添加到此DateTime

C# 将DateTimeOffset转换为DateTime并将偏移量添加到此DateTime,c#,datetime,datetimeoffset,C#,Datetime,Datetimeoffset,我有日期时间偏移量: DateTimeOffset myDTO = DateTimeOffset.ParseExact( "2015/01/15 17:37:00 -0500", "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture); Console.WriteLine(myDTO); 结果=>“

我有日期时间偏移量

    DateTimeOffset myDTO = DateTimeOffset.ParseExact(
                      "2015/01/15 17:37:00 -0500", "yyyy/MM/dd HH:mm:ss zzz", 
                      CultureInfo.InvariantCulture); 
Console.WriteLine(myDTO);
结果=>“2015年1月15日17:37:00-05:00”

如何转换为DateTime并在结果DateTime中添加此偏移量“-0500”

预期结果=>“1/15/2015 22:37:00

使用:


使用UTC时间时,不必将偏移量添加到时间。根据您的示例,您指的是UTC时间。这意味着您可以使用
DateTimeOffset.UtcDateTime
,就像我在这里演示的那样:

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

那会很奇怪。类似于
1/15/2015 17:37:00-05:00
的内容通常意味着“当地时间是17:37,但比UTC晚了5小时”——换句话说,
1/15/2015 22:37:00
的结果会很有用,因为这是UTC时间——但12:37会应用两次偏移。你能解释一下你的背景吗?@JonSkeet oops,我错了,我想成为“1/15/2015 22:37:00”,你可以使用,DateTimeOffset.DateTime属性,参考:。该死,你太快了:),不过对我来说这是一条路。
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