Skip to content

Quick Reference Guide: Add example of supporting Date field types in C# APIs #112

Description

@gstark

dotnet only has a DateTime and sometimes we want fields to just report a date.

Try this code to see if we can demonstrate how to format on both send and receive of api data as just a date:

[DataType(DataType.Date)]
[JsonConverter(typeof(JsonDateConverter))]
public DateTime InstallationDate { get; set; }

Also define this class:

class JsonDateConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
       => DateTime.ParseExact(reader.GetString(),
                    "yyyy-MM-dd", CultureInfo.InvariantCulture);
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
       => writer.WriteStringValue(value.ToString(
                    "yyyy-MM-dd", CultureInfo.InvariantCulture));
    }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions