I get a json string with number of milliseconds after 1970 from the server in my android app.
Looks like this: \/Date(1358157378910+0100)\/
.
How can I parse this into a Java calendar object, or just get some date value from it? Should I start with regex and just get the millisecons? The server is .NET.
Thanks
I think you can get like this:
json
it's aJsonElement
EDIT: You can send without the Date(), just the numbers, can't you? And if you are using JSON, why don't work with the Date Object?
Yeah, u can
substring
yourjson
from "(" to ")", convertstring
to millis and pass incalendar
object.Some of the other Answers such as by pablisco are correct about parsing the string to extract the number, a count of milliseconds since epoch. But they use outmoded date-time classes.
java.time
Java 8 and later has the java.time framework built-in. A vast improvement. Inspired by Joda-Time. Defined by JSR 310. Extended by the ThreeTen-Extra project. Back-ported to Java 6 & 7 by the ThreeTen-BackPort project, which is wrapped for Android by the ThreeTenABP project.
Consider the two parts of your input separately. One is a count from epoch in milliseconds, the other an offset-from-UTC.
Assuming the source used the same epoch as java.time (the first moment of 1970 in UTC), we can use that to instantiate an
Instant
object. AnInstant
is a moment on the timeline in UTC.Next we parse the offset-from-UTC. The trick here is that we do not know the intention of the source. Perhaps they meant the intended date-time is an hour behind UTC and so we should follow that offset text as a formula, adding an hour to get to UTC. Or they meant the displayed time is one hour ahead of UTC. The commonly used ISO 8601 standard defines the latter, so we will use that. But you really should investigate the intention of your data source.
We combine the
Instant
and theZoneOffset
to get anOffsetDateTime
.Dump to console.
Here is a more complete solution, based on @pablisco answer:
Try this..
Copied from the accepted answer, fixed some bugs :)