0

Formatting the date somehow is giving me an exception.

The date string that I want to convert to a Date object => 2019-12-12T15:31:31.000+0000

Code for converting which gives the error Text '2019-12-12T15:31:31.000+0000' could not be parsed at index 24

        Date date;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+'Z");
            ZonedDateTime formatDateTime = ZonedDateTime.parse(dateString,formatter);
            date = Date.from(formatDateTime.toInstant());

            return date.toString();

        }catch (Exception ex){
            return ex.getLocalizedMessage();
        }

I'm not sure why this isn't working, the Date has been a huge problem for me in Java. In C# there's hardly any work that needs to be done but I couldn't figure out how to parse a date string in Java.

Help is appreciated, thanks people.

oividiosCaeremos
  • 518
  • 1
  • 5
  • 20
  • 4
    `+` is already considered to be part of the zone pattern, so you can just end with `SSSZ`. You don't need the literal – Michael Dec 12 '19 at 17:03
  • 4
    Also, I strongly recommend that you keep the date in the `ZonedDateTime`. `java.util.Date` is trash, that's why they overhauled it with `java.time` – Michael Dec 12 '19 at 17:04
  • I removed the `+` from the pattern and the error vanished, but now it's returning the time as `18:31:31` instead of `15:31:31`. Timezone somehow is creating a problem even though I wrote both the code that inserted the date object into my database and the code that gets the date string into a date object. Any solutions about that? – oividiosCaeremos Dec 12 '19 at 17:08
  • 4
    As per previous recommendation, get rid of `java.util.Date`. Using `Date` for toString is a hack. Use a `DateTimeFormatter` to output it however you like – Michael Dec 12 '19 at 17:13
  • 2
    Read this related question and its answers : https://stackoverflow.com/questions/4216745/java-string-to-date-conversion – Jonathan Drapeau Dec 12 '19 at 17:19
  • Does this answer your question? [Convert date into AEST using java](https://stackoverflow.com/questions/48412345/convert-date-into-aest-using-java) And/or this? [Parsing a string to a datetime does not return the correct time](https://stackoverflow.com/questions/52152659/parsing-a-string-to-a-datetime-does-not-return-the-correct-time) – Ole V.V. Dec 12 '19 at 17:21
  • 1
    @JonathanDrapeau that link helped me with my problem, thanks. Michael also thank you for giving me the advice of how trash is java.util.Date. Thanks all guys. – oividiosCaeremos Dec 12 '19 at 17:36

0 Answers0