ServiceStack - Is there a way to force all serialized Dates to use a specific DateTimeKind?

 ̄綄美尐妖づ 提交于 2019-11-28 07:35:18

If you need something more configurable than @mythz's answer, you can force the serialization or deserialization of DateTimes to have a certain DateTimeKind by overriding the DateTime and optionally DateTime? serialization and/or deserialization methods.

Force all serialized DateTimes to be interpreted as UTC

JsConfig<DateTime>.SerializeFn = time => new DateTime(time.Ticks, DateTimeKind.Local).ToString();

You can then take this one step farther and error on deserialization if the DateTime isn't in a specified format. I started using this when I wanted to force clients to specify the timezone in all requests, but not necessarily require that it always be Utc.

JsConfig<DateTime>.DeSerializeFn = time =>
{
  if (!IsInCorrectDateFormat(time))
    throw new System.Runtime.Serialization.SerializationException(BadDateTime);

  return ServiceStack.Text.Common.DateTimeSerializer.ParseDateTime(time);
};

The DateTimeKind offset does not get stored with Date's so by default ServiceStack serializers make the assumption that the date is local, which gets serialized as UTC and deserialized back out as Local.

You can get DateTimeKind.Unspecified to be assumed as UTC with:

JsConfig.AssumeUtc = true;

A tweak to bpruitt-goddard solution. All credit goes to him.

JsConfig<DateTime>.SerializeFn = time => new DateTime(time.Ticks, DateTimeKind.Local).ToString("o");
        JsConfig<DateTime?>.SerializeFn = 
            time => time != null ? new DateTime(time.Value.Ticks, DateTimeKind.Local).ToString("o") : null;
        JsConfig.DateHandler = DateHandler.ISO8601;

So any dates going out from service stack will be forced into a ISO8601 date format and any dates coming in will be converted automatically to C# date from the ISO8601 string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!