Convert UTC DateTime to DateTimeOffset

Here is the solution you are looking for:

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

DateTimeOffset utc = DateTimeOffset.Parse(dateString);
DateTimeOffset 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));

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


Is this what you want:

[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);
}
  • Note that my asserts are valid in Sweden (CET)
  • There are a couple of overloads on DateTime.Parse()

Is this useful for your conversion:

[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);
}