繁体   English   中英

如何在Java / Android中解析JSON日期时间

[英]How to parse JSON date time in Java/Android

我到处都看过,但找不到任何有关在android中解析日期时间json对象的信息。

我想这个JSON转换2016-08-12T20:07:59.518451 得到这样的时间20:07 ,并在正确的时区UTC / GMT +1小时格式它。

我可以用javascript完成,但无法在Java / Android中正确使用。

有没有适合我的方法,还是需要使用Regex来获取正确的时间?

编辑:这是代码。 ExpectedArrival是带有json日期/时间的,我只想获取UTC / GMT +1小时时区的时间。

public class JSONTaskArrivals extends AsyncTask<String, String,List<ArrivalItem>> {

    @Override
    protected List<ArrivalItem> doInBackground(String... params) {
        //json
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";

            while((line = reader.readLine()) != null){
                buffer.append(line);
            }

            String finalJSON = buffer.toString();
            JSONArray parentArray = new JSONArray(finalJSON);
            List<ArrivalItem> arrivalItems = new ArrayList<>();
            int time = 0;
            for (int i = 0; i < parentArray.length(); i++){
                JSONObject finalObject = parentArray.getJSONObject(i);

                ArrivalItem item = new ArrivalItem();
                item.setDestination(finalObject.getString("destinationName"));
                item.setEstimated(finalObject.getString("expectedArrival"));
                time = finalObject.getInt("timeToStation")/60;
                if(time < 1){
                    item.setLive("Due");
                }else{
                    item.setLive(Integer.toString(time)+" mins");
                }

                arrivalItems.add(item);
            }

            return arrivalItems;


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null){
                connection.disconnect();
            }
            try {
                if (reader != null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<ArrivalItem> result) {
        super.onPostExecute(result);
        ArrivalsAdapter adapter = new ArrivalsAdapter(ArrivalsActivity.this, R.layout.arrivals_row, result);
        lv = (ListView) findViewById(R.id.arrivals_listView);
        lv.setAdapter(adapter);
    }
}

没有“ JSON日期时间”之类的东西。 JSON定义的数据类型很少

字符串→即时→OffsetDateTime→LocalTime

如果您的输入字符串2016-08-12T20:07:59.518451用UTC表示一个时刻,请附加一个Z (Zulu的缩写,表示UTC)。

String input = "2016-08-12T20:07:59.518451" + "Z" ;

然后解析为Instant Instant类表示UTC时间线上的时刻,分辨率为纳秒 因此,您的示例输入(以微秒为单位)非常合适。

Instant instant = Instant.parse( input );

调整为所需的UTC偏移量。

ZoneOffset offset = ZoneOffset.ofHours( 1 ); // One hour ahead UTC.

申请以获取OffsetDateTime

OffsetDateTime odt = instant.atOffset( offset );

如果你想只从时间的日OffsetDateTime提取LocalTime

LocalTime lt = odt.toLocalTime(); // Example: 20:39

如果要使用toString方法使用的ISO 8601格式以外的格式,请使用DateTimeFormatter对象。 如果在Stack Overflow上进行搜索,则会发现许多示例。

如果知道,最好使用时区,而不是仅使用时区。 产生一个ZonedDateTime对象。

ZoneId zoneId = ZoneId.of( "Europe/Paris" );
ZonedDateTime zdt = instant.atZone( zoneId );
LocalTime lt = zdt.toLocalTime();

关于java.time

java.time框架内置于Java 8及更高版本中。 这些类取代了麻烦的旧日期时间类,例如java.util.Date.Calendarjava.text.SimpleDateFormat

现在处于维护模式Joda-Time项目建议迁移到java.time。

要了解更多信息,请参见Oracle教程 并在Stack Overflow中搜索许多示例和说明。

多的java.time功能后移植到Java 6和7在ThreeTen-反向移植并且还适于使用AndroidThreeTenABP

ThreeTen-Extra项目使用其他类扩展了java.time。 该项目为将来可能在java.time中添加内容提供了一个试验场。

你应该做这个:

  1. 该json有一个key:val和日期,然后获取日期,(肯定是json中的字符串)
  2. 然后解析该字符串作为日期。
  3. 使用SimpleDateFormatter并格式化重建的日期以表示为您想要的/需要的。

您可以使用split方法拆分日期和时间,并将其存储在另外两个变量中。.现在,您有了日期和时间的单独值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM