Convert UTC DateTime to DateTimeOffset

后端 未结 3 1189
谎友^
谎友^ 2020-12-16 10:51

I need to convert UTC date strings to DateTimeOffsets.

This must work with a timezone which differs from the computers timezone.

相关标签:
3条回答
  • 2020-12-16 10:55

    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);
    }
    
    0 讨论(0)
  • 2020-12-16 11:00
    const String dateString = "2012-11-20T00:00:00Z"; 
    var offsetDate = DateTimeOffset.Parse(dateString); 
    var offsetDate2 = DateTime.Parse(dateString);
    

    Output is

    offsetDate  {20-11-2012 0:00:00 +00:00}    System.DateTimeOffset
    offsetDate2 {20-11-2012 1:00:00}           System.DateTime
    
    0 讨论(0)
  • 2020-12-16 11:08

    Here is the solution you are looking for:

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

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

    0 讨论(0)
提交回复
热议问题