This question already has an answer here:
- how to convert incoming Json date into java date format? 2 answers
I am receiving response of Date in JSON format like /Date(1521866513877+0530)/
which I want in format like this 24/03/2018 10:11:53
.
This question already has an answer here:
I am receiving response of Date in JSON format like /Date(1521866513877+0530)/
which I want in format like this 24/03/2018 10:11:53
.
If there's no native way to parse that, try this regex
pattern:
\/Date\((\d+)\+(\d+)\)\/
I'm not a java guy but regex is everywhere. I looks like the date is in miliseconds so you need to divide 1521866513877 / 1000
to get the timestamp. Here's a sample in PHP:
preg_match_all('/\/Date\((\d+)\+(\d+)\)\//i', '/Date(1521866513877+0530)/', $matches);
if ($matches[0]) {
$timestamp = $matches[1][0];
$offset = $matches[2][0];
echo date('m/d/Y H:i:s', (int)$timestamp / 1000);
}
The Gson class may help you to serialize format like that. And default it use a SimpleDateFormat object to serialize. Use GsonBuilder to get a new Gson object to serialize date format like 24/03/2018 10:11:53:
Gson gson = new GsonBuilder()
.setDateFormat("dd/MM/yyyy HH:mm:ss")
.create();
Use a regular expression to extract the individual pieces from the string. The 13 digit number is a count of milliseconds since the epoch. Parse it as a long and convert it to an Instant
(class from java.time
, the modern Java date and time API). Parse +0530
into a ZoneOffset
; it’s an offset of 5 hours 30 minutes ahead of UTC or GMT. Combine the Instant
and the ZoneOffset
into an OffsetDateTime
. Format it using a DateTimeFormatter
. That’s all.
If there are some of the pieces you still don’t know how to do, use your search engine. All of this is explained in several places on the Internet. If after reading the tutorials and the API documentation and trying your best you still get stuck, ask a much more specific question here on Stack Overflow. Remember to include a report of your research and your best attempt and how it fails. We will be able to help you much better from there.