且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将UTC日期时间转换为DateTimeOffset

更新时间:2023-02-03 17:16:05

这是您要寻找的解决方案:

Here is the solution you are looking for:

const string dateString = "2012-11-20T00:00:00Z";
var timezone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"); //this timezone has an offset of +01:00:00 on this date

var utc = DateTimeOffset.Parse(dateString);
var result = TimeZoneInfo.ConvertTime(utc, timezone);

Assert.AreEqual(result.Offset, new TimeSpan(1, 0, 0));  //the correct utc offset, in this case +01:00:00
Assert.AreEqual(result.UtcDateTime, new DateTime(2012, 11, 20, 0, 0, 0)); //equals the original date
Assert.AreEqual(result.DateTime, new DateTime(2012, 11, 20, 1, 0, 0));

请注意,您错误地测试了 .LocalDateTime 属性-始终会将结果转换为计算机的本地时区。您只需要 .DateTime 属性即可。

Note that you were incorrectly testing the .LocalDateTime property - which is always going to convert the result to the local timezone of the computer. You simply need the .DateTime property instead.