How to Convert JSON Date Format to Simple Date Format? [duplicate]

Deadly 提交于 2020-01-17 18:02:44

问题


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.


回答1:


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);
}



回答2:


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();  



回答3:


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.



来源:https://stackoverflow.com/questions/49461473/how-to-convert-json-date-format-to-simple-date-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!