Search code examples
javac#jsonexceptiondate-conversion

Convert part of string to java.util.Date


I am posting DateTime as JSON and it becomes "/Date(1512839439513)/"

i simply want to convert

"/Date(1512839439513)/"  to java.util.Date

I have tried this

String date = finalObject.getString("DateCreated");
String datereip = date.replaceAll("\\D+","");
Long timeInMillis = Long.parseLong(datereip);
Date date1=new Date(timeInMillis);

But did not worked...


Solution

  • The way you extract the milliseconds from the string seems to be the problem.

    You can try this to extract needed data from the string:

    String date = finalObject.getString("DateCreated");
    
    String temp = date.substring(date.indexOf("(") + 1);
    String datereip = date.substring(0, date.indexOf(")"));
    
    Long timeInMillis = Long.parseLong(datereip);
    Date date1=new Date(timeInMillis);
    

    This assumes that the date string will have only one pair of parenthesis. Also, there are better ways to extract string between 2 chars with Java but that is a topic of another question.