Daniel O Mensah
Daniel O Mensah

Reputation: 406

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.518451to 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);
    }
}

Upvotes: 0

Views: 4231

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338516

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.

Upvotes: 3

shahid17june
shahid17june

Reputation: 1577

You can use split method to split date and time and store it another two variable.. So now you have seprate values of date and time..

Upvotes: 0

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..

Upvotes: 3

Related Questions