C#C
C#4y ago
kopuo.

receiving, saving and returning UTC DateTime

Hi. In Api I get a DateTime from the client in UTC format - with "Z" at the end of the string. I want to save this date in UTC format in the database and then also return it in response in UTC format.

I used such a converter on input and output:
public class DateTimeConverter : JsonConverter<DateTime>
{
  public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  {
    var dateTime = DateTime.Parse(reader.GetString());

    return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
  }

  public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  {
    writer.WriteStringValue(DateTime.SpecifyKind(value, DateTimeKind.Utc));
  }
}


I use it in program.cs:
AddControllers().AddJsonOptions(options =>
{
  options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});


Is this action sufficient to save the incoming date in UTC format to the database? Incoming DateTime have Kind = UTC, as do outgoing ones with 'Z' at the end.
Was this page helpful?