c# - Still struggling with the JSON.net Dateformat -
i have problems transmitting date (in string format) our object, since serializer seems convert wrong time.
the format dd.mm.yyyy (swiss time format) , serializer tries convert mm-dd-yyyy (where days converted months).
so if have date 06.03.1992 (6th of march), converter makes 3rd of june. , if day higher 12, program crashes.
i know can specify date format somehow, haven't got working solution. ideas problem?
thanks in advance, daniel
you can control format json.net uses serializing , deserializing dates creating new instance of isodatetimeconverter class, setting datetimeformat property on require , passing converter serializer.
here demo:
class program { static void main(string[] args) { isodatetimeconverter dateconverter = new isodatetimeconverter { datetimeformat = "dd.mm.yyyy" }; foo foo = new foo { date = new datetime(2014, 3, 12) }; // serialize object containing date using custom date format string json = jsonconvert.serializeobject(foo, dateconverter); console.writeline(json); // deserialize json custom date format object foo foo2 = jsonconvert.deserializeobject<foo>(json, dateconverter); console.writeline("day = " + foo2.date.day); console.writeline("month = " + foo2.date.month); console.writeline("year = " + foo2.date.year); } } class foo { public datetime date { get; set; } } output:
{"date":"12.03.2014"} day = 12 month = 3 year = 2014 note: approach, date format applied all dates on objects serializing or deserializing. if require different formats different dates, see this question offers couple of possible solutions.
Comments
Post a Comment