Skip to content

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

@gstark

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));
    }

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