c# - Force JSON.NET to include milliseconds when serializing DateTime (even if ms component is zero) -


i'm using json.net serialize datetime values directly object instances (not using datetime.tostring() formatter).

is there way force json.net include milliseconds in serialization if millisecond component of datetime zero?

background: have slow web service consumer json endpoint. conditional logic expensive consumer, i'd provide same data formatting every time.

we ran same issue on current project. using web api (and hence json.net) implement rest api. discovered that, when serializing datetime objects, json.net omits trailing zeros milliseconds, or omits milliseconds date entirely if zero. our clients expecting fixed-length date-time string, 3 digits milliseconds. fixed doing following in application_start():

jsonserializersettings settings = httpconfiguration.formatters.jsonformatter.serializersettings; isodatetimeconverter dateconverter = new isodatetimeconverter  {      datetimeformat = "yyyy'-'mm'-'dd't'hh':'mm':'ss.fff'z'"  }; settings.converters.add(dateconverter); 

if you're not using web api, can same thing creating new instance of jsonserializersettings, adding isodatetimeconverter shown above, passing serializer settings jsonconvert.serializeobject().

note: if you're serializing datetimeoffset or local datetime , want include timezone offset, replace quoted 'z' in above format unquoted k. see custom date , time format strings in documentation more info.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -