【问题标题】:How to parse JSON date time in Java/Android如何在 Java/Android 中解析 JSON 日期时间
【发布时间】:2016-08-14 06:41:23
【问题描述】:

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

我正在尝试将此 JSON 2016-08-12T20:07:59.518451 转换为 20:07 这样的时间,并将其格式化为正确的时区 UTC/GMT +1 小时。

我可以在 javascript 中做到这一点,但我无法在 Java/Android 中做到这一点。

有没有一种方法可以为我处理这个问题,或者我需要使用正则表达式来获得正确的时间?

编辑:这是代码。 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);
    }
}

【问题讨论】:

  • 您可以尝试手动操作(例如,如果您在印度,请将您收到的时间增加 5 小时 30 分钟,如果日期也发生变化,请增加相应的日期)
  • @HarshitKumar 并没有真正的帮助。我想知道如何从那个 JSON 日期时间对象中获取时间
  • 发布代码以便我们改进帮助......
  • @ΦXocę웃Пepeúpaツ 我现在有代码

标签: java android json


【解决方案1】:

没有“JSON 日期时间”之类的东西。 JSON 定义了very few data types

String → Instant → OffsetDateTime → LocalTime

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

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

然后解析为InstantInstant 类代表UTC 时间线上的一个时刻,分辨率为nanoseconds。因此,您使用 microseconds 的示例输入非常适合。

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 项目现在位于maintenance mode,建议迁移到 java.time。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。

大部分 java.time 功能在ThreeTen-Backport 中向后移植到Java 6 和7,并进一步适应ThreeTenABP 中的Android

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。

【讨论】:

    【解决方案2】:

    你应该这样做:

    1. 那个 json 有一个 key:val 和日期,然后得到日期,(它肯定在 json 中作为字符串)
    2. 然后将该字符串解析为日期。
    3. 使用SimpleDateFormatter 并将重构日期格式化为您想要/需要的格式..

    【讨论】:

    • 这是正确的答案,看起来是yyyy-MM-ddTHH:mm:ss.fff的格式
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多