I am trying to parse date and time coming from the api. I am getting this kind of response "ArrivalTime":"\/Date(1543469400000)\/"
.How to parse this response?
CodePudding user response:
The 'envelope' looks like JSON to me, but you didn't paste much. Figure out what it is and get a library that can parse this, so that you end up with a single string that contains just the date part. The \/
looks bizarre, maybe that's a side effect of how you copy/pasted it. The string you want to end up with has as first character either that \
or more likely the D
from Date.
Once you have this:
private static final Pattern DATE_PATTERN = Pattern.compile("^\\\\/Date\\((\\d )\\)\\\\/$");
This pattern detects \/Date(any digits here)\/
and lets you extract the digits. If the \/
aren't in there, remove the 2 \\\\/
.
Then:
String d = "\/Date(1543469400000)\/"; // Get this from your json parser
Matcher m = DATE_PATTERN.matcher(d);
if (!m.matches()) throw new InvalidFormatEx();
long number = Long.parseLong(m.group(1));
Instant n = Instant.ofEpochMilli(number);
You now have the right data type - as that number sure looks like epoch-millis to me. It's 'zone less'. Whatever you actually intend to do - start with this instant and go from there.
For example, if you want to print it as a timestamp, zone it to whatever zone you want to print this at, and print it:
ZonedDateTime zdt = n.atZone(ZoneId.of("Europe/Amsterdam"));
System.out.println(zdt);
If you want to print it in specific formats, make a DateTimeFormatter
and calls ZDT's format
method, and so on.
CodePudding user response:
Simple Solution after getting it from JSON parser
val s = "\/ArrivalTime Date(1543469400000)\/" // yow can get it from JSON parser
val timeInMillis=s.substring(s.indexOf('(') 1, s.lastIndexOf(")"))
To format millis into Date
val date=DateFormat.getDateInstance().format(timeInMillis);