Reputation: 11658
I have a .NET WebAPI
which returns some dates as JSON
.
I'm using the Ok()
function which takes the C# DateTime list and convert them into a JSON array.
My requirement is to specify the timezone in any case (even +00:00)
Now, the format I'm using is:
jsonSerializerSettings.DateFormatString = "o";
which uses the ISO standard and a "Z" to specify UTC.
Unfortunately my web application doesn't understand such convention (I mean, the final "Z") and it requires a timezone offset to be present in any case. In other words, I'd like to use a "+00:00" instead of the "Z".
How can I tell WebAPI
to use such convention?
Previously I had:
jsonSerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffzzz";
which doesn't had the timezone information.
Upvotes: 0
Views: 1689
Reputation: 62298
Use System.DateTimeOffset instead of Use System.DateTime
in your return statement (Ok). This will automatically append the +00:00
the the serialized string (+00:00 is assuming its a UTC point in time).
for Web API 2 and higher, I am not sure about previous versions
This is also the default date/time format for other Web API extensions like oData.
Upvotes: 0
Reputation: 60674
This is not as easy as one would like - mainly, because the DateTime
type is confusing at its best, and wrong at its worst.
I would recommend handling only UTC dates on the server (i.e. assuming UTC on any incoming date, saving everything as UTC and returning UTC everywhere) and letting your clients decide if they need to do something about that (e.g. convert to a local time for correct display). Then, it could be as easy as setting
jsonSerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fff+00:00";
i.e. hard-coding the +00:00
there, since you know (by assumption) that it's going to be UTC.
Upvotes: 3