Brandon Hunt
Brandon Hunt

Reputation: 99

Serialize JSON date as yyyy-MM-ddTHH:mm:ss:fffzzzz without colon in the timezone

I am using NewtonSoft.JSON to serialize my object to JSON. I have a requirement where the datetime format has to be 2017-05-06T11:59:37:012-0500. I've passed in my own datetime format to get it to pass as this 2017-05-06T11:59:37:012-05:00. However I am uncertain how to remove the colon in the time zone.

Here is how you can convert it, but I need something where I can actually work with the string directly.

var postDataSerialized = JsonConvert.SerializeObject(postData, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss:fffzzzz" });

Upvotes: 2

Views: 2448

Answers (1)

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

Unfortunately, there is no way to avoid this colon just by adjusting some parameter value. IsoDateTimeConverter uses .Net DateTime custom format feature, and the colon is hardcoded for the zzz custom format.

Therefore you have to implement the desired formatting yourself, which can be done by providing a custom JsonConverter. The custom converter may look like this:

public class NoColonIsoDateTimeConverter : IsoDateTimeConverter
{
    public NoColonIsoDateTimeConverter()
    {
        DateTimeFormat = "yyyy'-'MM'-'ddTHH':'mm':'ss':'fffzzz";
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is DateTime)
        {
            var dateTime = (DateTime)value;
            var text = dateTime.ToString(DateTimeFormat);
            text = text.Remove(text.Length - 3, 1);
            writer.WriteValue(text);
        }
        else
        {
            throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime");
        }
    }
}

Demo: https://dotnetfiddle.net/79AuZs

Upvotes: 5

Related Questions