In JSON.NET you can:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
Is there anything similar in System.Text.Json
?
If there is not an option to set the default, can it be passed in manually?
Also, what is the default (Local
, Utc
, Unspecified
)?
cc @layomia on dates
Since a DateTime can be set in each of those formats (e.g. with and without the timezone\offset), the reader\writer (and thus the serializer) uses what is available and uses\assumes an ISO 8601 format to represent that.
@btecu the ISO 8601 profile is used by default in the serializer, e.g. 2019-07-26T16:59:57-05:00.
For deserializing, if the datetime offset is given as "hh:mm", a DateTime with DateTimeKind.Local
is created. "Z" will give DateTimeKind.Utc
. If no offset is given, then a DateTime with DateTimeKind.Unspecified
is created.
The reverse mapping applies to serialization: writing a DateTime
with DateTimeKind.Local
will yield an ISO representation with an "hh:mm"-formatted offset, and so on.
For more on DateTime and DateTimeOffset support in System.Text.Json, and how you can implement custom parsing or formatting, see https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support.
@btecu unfortunately the only way, I think, to have the similar option in System.Text.Json
is to do:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
and implement DateTimeConverter like that
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
}
}
Most helpful comment
@btecu unfortunately the only way, I think, to have the similar option in
System.Text.Json
is to do:and implement DateTimeConverter like that