简体   繁体   中英

How to parse JSON date time in Java/Android

I have looked everywhere but I couldn't find anything about parsing a date time json object in android.

I am trying to convert this JSON 2016-08-12T20:07:59.518451 to get ONLY the time like this 20:07 and format it in the correct time zone UTC/GMT +1 hour.

I could do it in javascript, but I wasn't able to get it right in Java/Android.

Is there a method that handle this for me or will I need to use Regex to get the correct time?

EDIT: here is the code. expectedArrival is the one with the json date/time and I only want to get the time with UTC/GMT +1 hour time zone.

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

No such thing as a “JSON date-time”. JSON defines very few data types .

String → Instant → OffsetDateTime → LocalTime

If your input string 2016-08-12T20:07:59.518451 represents a moment in UTC, append a Z (short for Zulu, means UTC).

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

Then parse as an Instant . The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds . So your example input with microseconds fits nicely.

Instant instant = Instant.parse( input );

Adjust into your desired offset-from-UTC.

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

Apply to get an OffsetDateTime .

OffsetDateTime odt = instant.atOffset( offset );

If you want only the time-of-day from that OffsetDateTime extract a LocalTime .

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

If you want other than the ISO 8601 format used by the toString method, use a DateTimeFormatter object. Many examples found if you search on Stack Overflow.

Better to use a time zone, if known, rather than a mere offset. Produces a ZonedDateTime object.

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

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to java.time.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP .

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

You should do this:

  1. That json has a key:val with the date, then get the date, (its for sure in the json as string)
  2. then parse that String as Date.
  3. use a SimpleDateFormatter and format the reconstructed date to be represented as you want/need..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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