-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
Background and motivation
Currently, System.Text.Json does not provide a way to control how DateTimeKind.Unspecified values are handled during serialization and deserialization.
This can lead to inconsistent behavior across systems, especially when working with APIs that require all dates to be UTC or Local.
Problem
Serialization: When DateTime.Kind == Unspecified, the serializer writes the value without a timezone offset, which can be misinterpreted by consumers.
Deserialization: When parsing a date string without an offset or Z suffix, the resulting DateTime has Kind == Unspecified, which can cause ambiguity and bugs in time-sensitive applications.
There is no built-in option to:
Force Unspecified to be treated as UTC or Local.
Automatically assign a Kind during deserialization.
API Proposal
namespace System.Text.Json
{
public enum DateTimeUnspecifiedKindHandling
{
AssumeUtc, // Treat as UTC
AssumeLocal // Treat as Local (default)
}
public partial class JsonSerializerOptions
{
public DateTimeUnspecifiedKindHandling DateTimeUnspecifiedKindHandling { get; set; }
}
}API Usage
var options = new JsonSerializerOptions
{
DateTimeUnspecifiedKindHandling = DateTimeUnspecifiedKindHandling.AssumeUtc
};
var json = JsonSerializer.Serialize(new { Date = new DateTime(2024, 01, 01) }, options);
// Output: {"Date":"2024-01-01T00:00:00Z"}
var obj = JsonSerializer.Deserialize<MyDto>("{\"Date\":\"2024-01-01T00:00:00\"}", options);
// obj.Date.Kind == DateTimeKind.UtcAlternative Designs
Workarounds Today
A custom JsonConverter can be implemented to enforce this behavior, but:
It must be manually registered.
It adds boilerplate for every project.
It’s easy to forget to apply it, leading to subtle bugs.
Rationale
Improves interoperability with APIs that require consistent date kinds.
Reduces ambiguity and potential time zone bugs.
Aligns with similar options in other serializers (e.g., Newtonsoft.Json’s DateTimeZoneHandling).
Alternatives
Continue using custom converters (less discoverable, more error-prone).
Post-process DateTime values after deserialization (inefficient).
Additional Context
This feature would be especially useful in:
Distributed systems where UTC is the standard.
Applications that must comply with strict date/time handling rules.
Migration scenarios from Newtonsoft.Json where DateTimeZoneHandling is already in use.
If you want, I can also add a working prototype implementation so the .NET team can see exactly how it could be integrated into System.Text.Json.
Risks
No response