A short post to note datetime formatter syntax.
When parsing JSON data from an API and serializing data to POCOs in C#, each JSON record contained a property created_at that indicated when the record was created.
For example:
{ "created_at": "Sun Mar 12 10:39:02 +0000 2023", "id": 1635228972349890560, "id_str": "1635228972349890560", "text": "{some text}", "truncated": true, "entities": { "symbols": [], "user_mentions": [] }, "in_reply_to_status_id": null, "in_reply_to_screen_name": null, "coordinates": null, "place": null "lang": "en" }
Problem
When using the default serializer with this data, a parsing exception is thrown when trying to map the field created_at to a DateTime object.
DataV1 responseDataDTO = JsonConvert.DeserializeObject<DataV1>(jsonResponse);
The Solution
The solution for this is to use DateTime.ParseExact, passing in the JSON, setting the following DateTime formatter, and setting the culture to Invariant
For example:
DataV1 responseDataDTO = JsonConvert.DeserializeObject<DataV1>(jsonResponse); DateTime parsedCreatedDate = DateTime.ParseExact(responseDataDTO.created_at, "ddd MMM dd HH:mm:ss +0000 yyyy", CultureInfo.InvariantCulture);
The output field (parsedCreatedDate) can then be used in the application
Resources
Learn and read more about DateTime.ParseExact here and InvariantCulture here.
Leave a Reply