Java – Convert Json date to java date

datetimegsonjavajson

My json respons contains a CreatedOn Date:

{
"CreatedOn" : "\/Date(1406192939581)\/"
}

I need to convert CreatedOn to a simple date format and count the days of difference from CreatedOn Date to Present Date.

When I debug the below code string CreatedOn showing a null value. How come?

JSONObject store = new JSONObject(response);

if (response.contains("CreatedOn"))
{
    String CreatedOn = store.getString("CreatedOn");
}   

Best Solution

JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
  Timestamp stamp = new Timestamp(store.getLong("CreatedOn"));
  Date date = new Date(stamp.getTime());
  System.out.println(date);
}

or

JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));
 Date date = new Date(datetimestamp);
 DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
 String dateFormatted = formatter.format(date);
}

consider using JSON methods instead of contains. JSON has "has()" which validate if key exists.

You should also make sure that you try {} catch {} the String first, to make sure its valid JSON.

Update:

Your Value is /Date(1406192939581)/

which means it must be formatted first. Get it by parsing the string with

Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));