ServiceStack.Text output UTC offset

本文关键字:offset UTC output Text ServiceStack | 更新日期: 2023-09-27 18:32:59

我最近将我的项目的ServiceStack.Text从3.9.23升级到最新的稳定版。

我有一些单元测试,确保我们输出的日期格式不会改变。它们现在在升级后失败。测试如下所示:

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

测试失败,因为ServiceStack.Text现在将UTC偏移量输出为零,这不是我想要的,所以我得到:

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

如何配置 ServiceStack.Text 以使用旧行为?

ServiceStack.Text output UTC offset

设置:

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

为我解决了问题,这基本上是我需要 DateTimes 与DateTimeKind.Unspecified一起被视为当地时间。我查看了ServiceStack.Text源,这个处理程序就是这样做的。请注意,在将字符串解析为 DateTime 输入时,处理程序会丢弃 UTC 偏移量并将时间视为本地时间。(幸运的是,这也适用于我的应用程序)。