MATLAB Answers

0

Convert JSON datetime-wire-format

Asked by Andrea Hoeing on 26 Jun 2019
Latest activity Commented on by Guillaume
on 27 Jun 2019
Hi,
there'is a way to convert a JSON datetime-wire-format in matlab datetime or datenum?
please see for specific datetime-wire-format
thank you

  0 Comments

Sign in to comment.

1 Answer

Answer by Peter Perkins
on 27 Jun 2019

This appears to be some kind of weird mix of a text and a numeric representation that includes milliseconds since 1-Jan-1970 UTC. My suggestion is to extract the main numeric part of that text (700000 in the example you point to) and use the datetime constructor and 'ConvertFrom'.
The time zone portion appears to be pretty much useless on its own. There are any number of time zones that at some point in the year have a UTC offset of 5 hours (+0500 from the example) and no way to disambiguate that. The description you point to says, "the number of milliseconds in the GMT time zone", which is already almost certainly wrong, it's UTC not GMT, but in any case, I'd just ignore any time zone portion and use some other information to correctly localize the time stamp.

  1 Comment

Guillaume
on 27 Jun 2019
With regards to the timezone offset, the doc actually says that "the actual number ("0500" in this example) and its sign (+ or -) are ignored.". It seems the sole point of it is that if it's present the first part must be considered local time (regardless of which timezone the time was originally in), if it's omitted, the first part is UTC. That doesn't sound very well designed (I'm surprised by that, .Net is usually very well thought out).
In any case, you won't be able to override the way jsondecode decode this. It will be decoded as a string. Afterward you could convert it to datetime:
%input: jsonelement: the Date json string to be deserialised, a char vector or a scalar string
%output: deserialised: the deserialised datetime
tokens = regexp(jsonelement, '/Date\((\d+)([+-]\d+)?\)/', 'tokens', 'once');
assert(~isempty(tokens), 'Invalid Date encoding');
if isempty(tokens{2})
tz = 'UTC';
else
tz = 'local';
end
deserialised = datetime(str2double(tokens{1}), 'ConvertFrom', 'posixtime', 'TimeZone', tz);
However, note that matlab's jsondecode can't be reliably used to deserialise json as it may irreversibly mangle the name part of name/value pairs (as it convert names to valid variable names).

Sign in to comment.