Convert UTC DateTime to DateTimeOffset
我需要将
这必须使用与计算机时区不同的时区。
例如。 当前计算机时区是+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)
当然,必须考虑夏令时。
编辑:
为了使事情更加清晰,请尝试完成以下代码段:
1 2 3 4 5 6 7 8 9 | 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)); |
这是您正在寻找的解决方案:
1 2 3 4 5 6 7 8 9 | 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)); |
请注意,您错误地测试了
这是你想要的吗:
1 2 3 4 5 6 7 8 | [Test] public void ParseUtcDateTimeTest() { DateTime dateTime = DateTime.Parse("2012-11-20T00:00:00Z"); Assert.AreEqual(new DateTime(2012, 11, 20, 01, 00, 00), dateTime); DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime); Assert.AreEqual(new TimeSpan(0, 1, 0, 0), dateTimeOffset.Offset); } |
- 请注意,我的断言在瑞典(CET)有效
-
DateTime.Parse() 上有几个重载
这对您的转化有用:
1 2 3 4 5 6 7 8 9 10 | [Test] public void ConvertTimeTest() { DateTime dateTime = DateTime.Parse("2012-11-20T00:00:00Z"); TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); DateTime convertedTime = TimeZoneInfo.ConvertTime(dateTime, cstZone); Assert.AreEqual(new DateTime(2012, 11, 19, 18, 00, 00), convertedTime); TimeSpan baseUtcOffset = cstZone.BaseUtcOffset; Assert.AreEqual(new TimeSpan(0, -6, 0, 0), baseUtcOffset); } |
1 2 3 | const String dateString ="2012-11-20T00:00:00Z"; var offsetDate = DateTimeOffset.Parse(dateString); var offsetDate2 = DateTime.Parse(dateString); |
输出是
1 2 | offsetDate {20-11-2012 0:00:00 +00:00} System.DateTimeOffset offsetDate2 {20-11-2012 1:00:00} System.DateTime |