Search code examples
javaparsingjodatime

Lost date while converting/parsing String to Datetime Java


DateTimeFormatter dateFormatter1 =
        DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

String timestamp = "2021-02-03 23:22:23 +0000 UTC";

DateTime converted1 = dateFormatter1.parseDateTime(timestamp);

Invalid format: "2021-02-03 23:22:23 +0000 UTC" is malformed at " 23:22:23 +0000 UTC"
java.lang.IllegalArgumentException: Invalid format: "2021-02-03 23:22:23 +0000 UTC" is malformed at " 23:22:23 +0000 UTC"

Getting an exception while parsing String to Datetime Java, can anyone please help?

Tried various formats like:

yyyy-MM-dd'T'HH:mm:ss'Z'
yyyy-MM-dd'T'HH:mm:ssZ
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
yyyy-MM-dd HH:mm:ss.SSS
(yyyy-MM-dd'T'HH:mm:ss'Z').withZone(UTC)

Solution

  • Your pattern is not correct. Use yyyy-MM-dd HH:mm:ss Z z

    import org.joda.time.DateTime;
    import org.joda.time.format.DateTimeFormat;
    import org.joda.time.format.DateTimeFormatter;
    
    public class Main {
        public static void main(String[] args) {
            String timestamp = "2021-02-03 23:22:23 +0000 UTC";
            DateTimeFormatter fmtInput = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss Z z");
    
            DateTime dtSource = fmtInput.parseDateTime(timestamp);
            System.out.println(dtSource);
        }
    }
    

    Output:

    2021-02-03T23:22:23.000Z