Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force ISO format "YYYY-MM-DDThh:mm:ss.sss" on the JSON output?

I have an ASP .NET WebApi2 api which returns some timestamps in JSON format. The timestamps have milliseconds resolution.

Usually I got timestamps of this format which is fine "YYYY-MM-DDThh:mm:ss.sss"

Unfortunately, if a timestamp happens to encode a date with whole second the output format is "YYYY-MM-DDThh:mm:ss" (note the missing .sss")

How to force ISO format "YYYY-MM-DDThh:mm:ss.sss" on the JSON output all the time?

like image 998
Gianluca Ghettini Avatar asked Sep 28 '22 01:09

Gianluca Ghettini


1 Answers

Add this line to WebApiConfig.Register

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
       // existing stuff

       config.Formatters
            .JsonFormatter
            .SerializerSettings
            .DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK";
    }
}

The default format is "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK" which gives up to 6 dp. I guessed at lowercase f and it appears to work.

Note the K is timezone (or Z for UTC) it also shows blank for unknown date types which is why you don't have anything showing there.

like image 53
weston Avatar answered Oct 03 '22 08:10

weston