1

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

Tadija Bagarić
  • 2,495
  • 2
  • 31
  • 48
Inshal Irshad
  • 227
  • 3
  • 17
  • 1
    If it did not work, what did it do instead? What did you expect it to do? What did you find when you debugged it? – Andy Turner Dec 10 '17 at 10:59
  • 1
    Why is this tagged both with java and c#? What date this this number represents? (seems like epoch time) – Zohar Peled Dec 10 '17 at 11:01
  • `System.out.println(new Date(Long.parseLong("/Date(1512839439513)/".replaceAll("\\D+",""))));` outputs `Sat Dec 09 19:10:39 EET 2017`, so the question is what is returned by `finalObject.getString("DateCreated")`. Have you used a debugger before? – mihail Dec 10 '17 at 11:04
  • 1
    Why don't you send the date in a standardized format instead of whatever that is? – Joe C Dec 10 '17 at 11:15
  • @JoeC agree, this has nothing to valid JSON – Jacek Cz Dec 10 '17 at 11:19
  • Possible duplicate of [Convert Json date to java date](https://stackoverflow.com/questions/24956396/convert-json-date-to-java-date) – Ole V.V. Dec 11 '17 at 07:54
  • Please for your own sake search before posting your question. This one has been asked and answered a couple of times before. – Ole V.V. Dec 11 '17 at 07:55
  • Any particular reason why you are asking for an instance of the long outmoded `Date` class? Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 11 '17 at 11:42

1 Answers1

0

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.

Tadija Bagarić
  • 2,495
  • 2
  • 31
  • 48