سؤال

I recently upgraded ServiceStack.Text for my project from 3.9.23 to latest stable.

I have some unit tests in place ensuring that the date format we output does not change. They are now failing after the upgrade. The test looks like this:

[Test]
[TestCase(2012, 06, 22, 03, 26, 23, 837, "\"\\/Date(1340328383837+0200)\\/\"")] // Daylight savings time test in DK (+0200)
[TestCase(1997, 10, 30, 11, 23, 49, 060, "\"\\/Date(878207029060+0100)\\/\"")]
[TestCase(2050, 01, 14, 00, 00, 00, 000, "\"\\/Date(2525727600000+0100)\\/\"")] 
public void SerializeDate_ReturnsExpectedOutput(int year, int month, int day, int hour, int minute, int second, int ms, string expected)
{
    var dt = new DateTime(year, month, day, hour, minute, second, ms).ToUniversalTime();
    dt = TimeZoneInfo.ConvertTimeFromUtc(dt, TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));

    string serialized = ServiceStack.Text.JsonSerializer.SerializeToString(dt);

    Assert.AreEqual(expected, serialized, "DateTime Serialization failure, got {0} but expected {1} for DateTime = {2}",
        serialized, expected, dt);
}

The test fails because ServiceStack.Text now outputs the UTC offset as zero, which is not what I want, so I get:

  String lengths are both 30. Strings differ at index 21.
  Expected: ""\\/Date(1340328383837+0200)\\/""
  But was:  ""\\/Date(1340328383837-0000)\\/""
  ---------------------------------^

How can I configure ServiceStack.Text to use the old behavior ?

هل كانت مفيدة؟

المحلول

Setting:

ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.JsonDateHandler.DCJSCompatible;

Solves the problem for me, which was basically that I needed DateTimes with DateTimeKind.Unspecified to be treated as if they where local time. I looked into the ServiceStack.Text source, and this handler does just that. Just be aware that the handler throws away the UTC offset and treats the time as local time when parsing a string as DateTime input. (Which luckily also works for my app).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top