Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

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)
question from:https://stackoverflow.com/questions/66051813/lost-date-while-converting-parsing-string-to-datetime-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...