我需要将UTC
日期字符串转换为DateTimeOffsets
。
这必须适用于与计算机时区不同的时区。 例如,当前计算机时区为+02:00,但我想要创建一个偏移量为-4:00的DateTimeOffset。
我已经在stackoverflow上阅读了很多问题,但没有解决我的问题。
这就是我需要做的:
输入:"2012-11-20T00:00:00Z"
输出:具有以下属性的DateTimeOffset:
- UtcDateTime: 2012-11-20 00:00
- 定义时区的正确UTC偏移量(在此示例中为01:00)
- LocalDateTime: 2012-11-20 01:00 (= UtcDateTime + Offset)
当然,必须考虑夏令时。
编辑: 为使事情更加清晰,请尝试完成以下代码片段:
DateTimeOffset result;
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
//do conversion here
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.LocalDateTime, new DateTime(2012, 11, 20, 1, 0, 0));
var
并没有问题,但我同意显式类型声明可以使示例更清晰。我已经相应地编辑了答案。请记住,原始答案是8年前发布的。此外,您也可以提出编辑建议,而不是抱怨。 - Matt Johnson-Pint