Successfully added
React
by Patrik
ASP.NET Core: Parsing and Storing UTC Datetimes
ASP.NET Core with System.Text.Json
handles ISO 8601 UTC strings automatically when binding to DateTime
properties. Ensure you're not converting to UTC again if the incoming data already ends with Z
.
Best Practices:
[JsonPropertyName("created")]
public DateTime Created { get; set; } // Will be parsed as UTC if ends in "Z"
If needed, ensure correct serialization:
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new UtcDateTimeConverter() }
};
Custom converter (if required):
public class UtcDateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> DateTime.SpecifyKind(reader.GetDateTime(), DateTimeKind.Utc);
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
}
aspnetcore
utc
json
datetime
serialization
Referenced in:
Comments