Converting JSON object to util.Date in Java Converting JSON object to util.Date in Java json json

Converting JSON object to util.Date in Java


If possible, have the server return the date in a better format like ISO-8601 since that will avoid ambiguity and will result in smaller JSON payload.

If that is not possible, you will have to decide what parts of the JSON to use, either the time or the different values like hours, minutes, ... By manually picking out those parts, you can build a Date object manually using one of its constructors or via a java.util.Calendar object (since many constructors in java.util.Date are deprecated in Java 8).


This is what solved it. Thank you Ayush Gupta for the comment.

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {        @Override        public void onResponse(String response) {            try {                JSONObject jsonObject = new JSONObject(response);                timestamp = jsonObject.getLong("time");                lastLoadedDate = new Date(timestamp);            } catch (JSONException e) {                //Handle the exception            }        }    }


You can generate it yourself if you want to use java's util.Date.

In documentation you can find the proper contructor declaration as Date(int year, int month, int date, int hrs, int min, int sec).

So you can create it from json, you just have to get proper values out of it (in a way that your json object is specifed-> in my example it is an Object):

Date date = new Date(jsonElement.get(year), jsonElement.get(month), jsonElement.get(date), jsonElement.get(hrs), jsonElement.get(min), jsonElement.get(sec));