【发布时间】:2012-12-05 16:47:23
【问题描述】:
我需要将UTC 日期字符串转换为DateTimeOffsets。
这必须使用与计算机时区不同的时区。 例如。当前计算机时区为 +02:00,但我想创建一个偏移量为 -4:00 的 DateTimeOffset。
我已经在这里阅读了很多关于 stackoverflow 的问题,但没有一个能解决我的问题。
这就是我需要做的:
输入:“2012-11-20T00:00:00Z”
输出: DateTimeOffset with:
- UtcDateTime of 2012-11-20 00:00
- 已定义时区的正确 Utc 偏移量(本例中为 01:00)
- LocalDateTime:2012-11-20 01:00(= UtcDateTime + Offset)
当然必须考虑夏令时。
编辑: 为了让事情更清楚,请尝试完成以下代码sn-p:
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));
【问题讨论】:
标签: c# .net datetime datetimeoffset