问题
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter utcFormatter = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss zzz yyyy");
DateTime dateTime1 = utcFormatter.parseDateTime("Thu Mar 28 12:26:50 UTC 2019");
DateTimeZone istZone = DateTimeZone.forID("Asia/Kolkata");
DateTimeFormatter istFormatter = utcFormatter.withZone(istZone);
String dtstrIndiaTimezone = istFormatter.print(dateTime1);
System.out.println(dtstrIndiaTimezone);
DateTime dateTime2 = istFormatter.parseDateTime(dtstrIndiaTimezone);// throws exception
// System.out.println(dateTime2);
}
}
Executing the code given above shows the date time string in IST but throws the following exception when trying to parse the same:
Thu Mar 28 17:56:50 IST 2019
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "Thu Mar 28 17:56:50 IST 2019" is malformed at "IST 2019"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)
at Main.main(Main.java:16)
How to do it? Is it a bug in the API?
Note: I know how to do it using java.time
classes.
回答1:
I am sorry, you can’t. The documentation says:
Zone names: Time zone names ('z') cannot be parsed.
From the documentation of DateTimeFormat
来源:https://stackoverflow.com/questions/60120746/how-to-parse-date-time-string-in-india-timezone-using-joda-date-time-api-2-10-1