Convert DateTimeConverter from UTC string

I have a date serialized as the string "2012-06-20T13: 19: 59.1091122Z"

Using a DateTimeConverter , it is converted to a DateTime object {22: 49: 59.1091122} using Kind set to "Local".

eg. The following test failed:

    private static readonly DateTime UtcDate = new DateTime(634757951991091122, DateTimeKind.Utc);
    private const string UtcSerialisedDate = "2012-06-20T13:19:59.1091122Z";

    [Test]
    public void DateTimeConverter_Convert_From_Utc_String()
    {
        // Arrange
        var converter = TypeDescriptor.GetConverter(typeof(DateTime));

        // Act
        var result = converter.ConvertFrom(UtcSerialisedDate);

        // Assert
        Assert.AreEqual(UtcDate, result);
        Assert.AreEqual(DateTimeKind.Utc, ((DateTime)result).Kind);
    }

I am a little surprised by this ... I would expect the DateTime object returned by the converter to be in UTC.

The docs say that DateTimeConverter uses DateTime.Parse , but I assume that it should not use DateTimeStyles.RoundtripKind .

Is there any way around this?

+5
source share
1

, DateTime.Parse() DateTimeStyles - "Z" , UTC. MS, .

, , , DateTimeConverter TypeConverter , , , DateTimeStyles. , - . Culture.CurrentCulture, DateTimeStyles - , - .

, , , ? ? , :

public static object ConvertFrom<T>(string value)
{
  if (typeof(T) == typeof(DateTime))
    return DateTime.Parse(value, null, DateTimeStyles.RoundtripKind);

  var converter = TypeDescriptor.GetConverter(typeof(T));
  return converter.ConvertFrom(value);
}

DateTimeOffsetConverter - Z. .UtcDateTime , DateTime UTC.

+6

All Articles