我需要将UTC
日期字符串转换为DateTimeOffsets
。
这必须使用与计算机时区不同的时区。 例如。当前计算机时区是+02:00,但我想创建一个偏移-4:00的DateTimeOffset。
我已经在stackoverflow上阅读了很多问题,但没有一个能解决我的问题。
这就是我需要做的事情:
输入:“2012-11-20T00:00:00Z”
输出:DateTimeOffset:
当然必须考虑夏令时。
修改: 为了使事情更加清晰,请尝试完成以下代码段:
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));
答案 0 :(得分:13)
以下是您正在寻找的解决方案:
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
属性。
答案 1 :(得分:4)
这就是你想要的:
[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);
}
DateTime.Parse()
这对您的转化非常有用:
[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);
}
答案 2 :(得分:-1)
const String dateString = "2012-11-20T00:00:00Z";
var offsetDate = DateTimeOffset.Parse(dateString);
var offsetDate2 = DateTime.Parse(dateString);
输出为
offsetDate {20-11-2012 0:00:00 +00:00} System.DateTimeOffset
offsetDate2 {20-11-2012 1:00:00} System.DateTime