问题
Task to solve:
Given a DateTimeOffset
, its value has a particular Offset. I would like to serialize it with the exact form as it was represented, with that exact date and time value and exact same Offset value
Problem
Currently when serializing the moment is correct, but the formatted serialized version of the point in time is converted to the offset which is according to the current timezone. (This way although the point in time remains correct, but the original offset information lost)
Example
Given a DateTimeOffset
with date: 2019-07-26 and time: 00:00:00 and offset: -05:00
In a system when the current timezone gives the result the this particular date and time has offset +01:00, the DateTimeOffset will be serialized as:
2019-07-26T00:06:00+01:00
I would like to serialize it as
2019-07-26T00:00:00-05:00
I do know the two is equal moment of time. I also do know the difference between timezone and offset, and was careful when phrased when the current timezone gives the result the this particular date and time has offset +01:00
In our persistence and business records not only the exact point in time matters, but the offset itself also has meaning.
What I've tried:
As I see the automatic equality conversion to the current timezone's offset is done in Utf8JsonWriter
It is not designed to customization or inheritance. I've tried to implement a custom converter, but it is pretty much higher level where the customization must be injected...
public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTimeOffset>
{
public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
{
// Based on the experience I've described in the OP, it is useless
// to anything with the `DateTimeOffset value` because regardless its Offset, Utf8JsonWriter will write it with the current timezone's offset for the date.
}
}
回答1:
System.Text.Json
supports serialization in local timezone or UTC.
you definitely seem aware of this.
Other way solving your problem is converting between timezones. see this link: https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones#converting-between-any-two-time-zones
来源:https://stackoverflow.com/questions/61984200/how-to-affect-timezone-when-serializing-datetimeoffset-with-system-text-json