-1

How to convert the string to a date

In the string we have a timestamp (for example "2018-07-11T04:40:30Z"), and I want to simply convert this String time to 11-07-2018 16:40:30

String Time =  jresponse.getString("timestamp");
SimpleDateFormat sf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = sf.parse(Time);

I tried many times this code and it doesn't work because I have always this format "2018-07-11T04:40:30Z" and not this 11-07-2018 16:40:30 why ?

Arda Arslan
  • 1,331
  • 13
  • 24
jackojack
  • 1
  • 2
  • What is your error ? – antoine.lange Jul 11 '18 at 14:47
  • The format don't change I have always this 2018-07-11T04:40:30Z and not this format 11-07-2018 16:40:30 – jackojack Jul 11 '18 at 14:49
  • https://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date may help your issue. – theMaestro73 Jul 11 '18 at 14:51
  • Welcome to Stack Overflow! Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. Use the [edit] link to improve your *question* - do not add more information via comments. Thanks! – GhostCat Jul 11 '18 at 14:51
  • I would take a look at [this answer](https://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date#answer-20578792) and its Android specific notes at the end. In a nutshell, I think that format would be compatible with the `java.time` package found in most recent Android versions or alternatively with the [ThreeTen-Backport for Android](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). Either one also provides useful methods for date, time and datetime handling, so they are not only useful for parsing. – Markus Kauppinen Jul 11 '18 at 15:02
  • Consider dropping both `SimpleDateFormat` and `Date` since both are long outdated. [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/), is so much nicer to work with. `Instant.parse("2018-07-11T04:40:30Z"` gives you an `Instant` (the replacement for `Date`) even without an explicit formatter. – Ole V.V. Jul 11 '18 at 21:44
  • 1
    I have added a second original question in the “This question already has an answer here” box. I think it may be more helpful than the first. I particularly recommend my own answer there, of course. :-) – Ole V.V. Jul 12 '18 at 07:04

1 Answers1

1

If you want to parse dates like "2018-07-11T04:40:30Z"then you should change the format as "dd-MM-yyyy HH:mm:ss" will never work with that date. The correct format should be something like yyyy-MM-dd'T'HH:mm:ssZ.

Lorelorelore
  • 3,335
  • 8
  • 29
  • 40