If you have been working with C# and JSON you mmight probably resorted to Newtonsoft.Json, the defacto standard in .NET for handling JSON related data. However, when it comes to […]
If you have been working with C# and JSON you mmight probably resorted to Newtonsoft.Json, the defacto standard in .NET for handling JSON related data.
However, when it comes to parsing date and time related information you might have noticed that the intrinsic JTokenType.Date data type is missing a crucial piece – it does not provide time zone offset. Go searching for Newtonsoft Json timezone and you know what I mean.
Despite the fact that Newtonsoft allows you to defined a default behaviour for handling time zone information, it leaves you no choice to manually have a look at the original json string after you parsed an arbitrary json string.
Of course you can override JsonSerialiserSettings or provide your own when serialising and deserialising objects and json strings. But you cannot intercept the generic JToken.Parse method and supply a custom inspection oder conversion.
However, there is a workarodund for this by manually getting the corresponding json string from a parse JTokenType.Date token.
After you parsed that object with JToken.Parse(/* json string */); you end up with a hierarchy of JTokens that you process. A quick view at the token reveals that the Z is gone missing, so you no longer know if a local or UTC time was specified in the original string.
JsonDateTimeZulu
However you see that the parent object of our JToken still contains the full json string. So in order to get it we can use the following (a bit quirky code) to retrieve that information (error checking has been omitted to improve readability):
var DOUBLE_QUOTE = '"';
var DATE_TIME_PROPERTY_SEGMENT = 3;
var dateJTokenAsJValue = jToken as JValue;
// first get the Parent which still holds the original json string ...
var parentOfDateJTokenAsJValue = dateJTokenAsJValue.Parent;
// ... and convert it to a string ...
var dateTimePropertyAsString = parentOfDateJTokenAsJValue.ToString();
// ... dateTimePropertyAsString now effectively holds '"DateTimeZulu":"1970-01-01T02:00:00Z"'
// now we split the string into an array (based on the double quotes) ...
var dateTimePropertyAsStringArray = dateTimePropertyAsString.Split(DOUBLE_QUOTE);
// ... and take the 3rd segment which holds the actual json date time string
var dateTimeString = dateTimePropertyAsStringArray[DATE_TIME_PROPERTY_SEGMENT];
From then on you can use something like DateTimeOffset.TryParseExact or similar to validate the date and time format including time zone information.
This surely is quirky but as far as of today I did not find any better (or equally good) solution to get that information (which I tested with Newtonsoft.Json v6.0.8).