Convert Json date to java date

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

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", ""));

java.time

It’s about time that someone provides the modern answer. When this question was asked in 2014, Java 8 had just come out, and with it java.time, the modern Java date and time API. Today I recommend we all use this and avoid the old classes Timestamp, Date, DateFormat and SimpleDateFormat used in the other answer. The old classes were poorly designed and were replaced for a good reason.

Edit: With Java 8 you can directly parse your string from JSON into an Instant using an advanced formatter, which I consider quite elegant:

    DateTimeFormatter jsonDateFormatter = new DateTimeFormatterBuilder()
            .appendLiteral("/Date(")
            .appendValue(ChronoField.INSTANT_SECONDS)
            .appendValue(ChronoField.MILLI_OF_SECOND, 3)
            .appendLiteral(")/")
            .toFormatter();

    String createdOn = "/Date(1406192939581)/";
    Instant created = jsonDateFormatter.parse(createdOn, Instant::from);
    System.out.println("Created on " + created);

Output from this snippet is:

Created on 2014-07-24T09:08:59.581Z

The formatter knows that the last 3 digits are milliseconds of the second and considers all the preceding digits seconds since the epoch, so this works the way it should. To count the days of difference from CreatedOn Date to Present Date:

    ZoneId zone = ZoneId.of("Antarctica/South_Pole");
    long days = ChronoUnit.DAYS.between(created.atZone(zone).toLocalDate(), LocalDate.now(zone));
    System.out.println("Days of difference: " + days);

Output today (2019-12-20):

Days of difference: 1975

Please substitute your desired time zone if it didn’t happen to be Antarctica/South_Pole.

Original answer:

    final Pattern jsonDatePattern = Pattern.compile("/Date\\((\\d+)\\)/");

    String createdOn = "/Date(1406192939581)/";
    Matcher dateMatcher = jsonDatePattern.matcher(createdOn);
    if (dateMatcher.matches()) {
        Instant created = Instant.ofEpochMilli(Long.parseLong(dateMatcher.group(1)));
        System.out.println("Created on " + created);
    } else {
        System.err.println("Invalid format: " + createdOn);
    }

Output is:

Created on 2014-07-24T09:08:59.581Z

I am using a regular expression not only to extract the number from the string, but also for validation of the string.

The modern Instant class represents a point in time. It’s toString method renders the time in UTC, so this is what you see in the output, denoted by the trailing Z.

Link: Oracle tutorial: Date Time explaining how to use java.time.