Table of Contents

Class DateTimeConverter

Namespace
Cuemon.Extensions.Text.Json.Converters
Assembly
Cuemon.Extensions.Text.Json.dll

Provides a DateTime converter that can be configured like the Newtonsoft.JSON equivalent.

public class DateTimeConverter : JsonConverter<DateTime>
Inheritance
DateTimeConverter
Inherited Members
Extension Methods

Examples

DateTimeConverter enables custom format and culture-aware serialization of DateTime values in System.Text.Json. This example registers the converter in JsonSerializerOptions with the French date format "dd/MM/yyyy" and fr-FR culture, then serializes a UTC DateTime (2026-06-16). The JSON output contains the date as "16/06/2026". Deserializing the same JSON back to a DateTime and formatting it again with "dd/MM/yyyy" produces "16/06/2026", confirming round-trip fidelity with culture-aware formatting.

using System;
using System.Globalization;
using System.Text.Json;
using Cuemon.Extensions.Text.Json.Converters;

namespace MyApp.Examples;

public class DateTimeConverterExample
{
    public void Demonstrate()
    {
        var options = new JsonSerializerOptions();

        // Register a converter that writes dates in the French "dd/MM/yyyy" format
        options.Converters.Add(new DateTimeConverter("dd/MM/yyyy", new CultureInfo("fr-FR")));

        var original = new DateTime(2026, 6, 16, 14, 30, 0, DateTimeKind.Utc);

        string json = JsonSerializer.Serialize(original, options);
        Console.WriteLine(json); // "16/06/2026"

        var restored = JsonSerializer.Deserialize<DateTime>(json, options);
        Console.WriteLine(restored.ToString("dd/MM/yyyy")); // 16/06/2026

}
}

Constructors

DateTimeConverter(string, CultureInfo)

Initializes a new instance of the DateTimeConverter class.

public DateTimeConverter(string format = "O", CultureInfo provider = null)

Parameters

format string

A standard or custom date and time format string.

provider CultureInfo

An object that supplies culture-specific formatting information.

Methods

Read(ref Utf8JsonReader, Type, JsonSerializerOptions)

Reads and converts the JSON to DateTime.

public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

Parameters

reader Utf8JsonReader

The Utf8JsonReader to read from.

typeToConvert Type

The Type being converted.

options JsonSerializerOptions

The JsonSerializerOptions being used.

Returns

DateTime

The converted value.

Write(Utf8JsonWriter, DateTime, JsonSerializerOptions)

Write the value as JSON.

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)

Parameters

writer Utf8JsonWriter

The Utf8JsonWriter to write to.

value DateTime

The value to convert.

options JsonSerializerOptions

The JsonSerializerOptions being used.

See Also