Convert JSON datetime-wire-format

9 visualizaciones (últimos 30 días)
Andrea Hoeing
Andrea Hoeing el 26 de Jun. de 2019
Comentada: Guillaume el 27 de Jun. de 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

Respuestas (1)

Peter Perkins
Peter Perkins el 27 de Jun. de 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 comentario
Guillaume
Guillaume el 27 de Jun. de 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).

Iniciar sesión para comentar.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by