I want to convert to this string to LocalDateTime
object. How can I do that?
"Thu Aug 29 17:46:11 GMT+05:30 2019"
I already try something, but it didn't work.
final String time = "Thu Aug 29 17:46:11 GMT+05:30 2019";
final String format = "ddd MMM DD HH:mm:ss 'GMT'Z YYYY";
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(format);
LocalDateTime localDateTime = LocalDateTime.parse(time, dateTimeFormatter);
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "Thu Aug 29 17:46:11" at org.joda.time.format.DateTimeFormatter.parseLocalDateTime(DateTimeFormatter.java:900) at org.joda.time.LocalDateTime.parse(LocalDateTime.java:168)
Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to
java.time
(JSR-310).
This is quoted from the Joda-Time home page. I should say that it endorses the answer by Basil Bourque. In any case if you insist on sticking to Joda-Time for now, the answer is:
final String time = "Thu Aug 29 17:46:11 GMT+05:30 2019";
final String format = "EEE MMM dd HH:mm:ss 'GMT'ZZ YYYY";
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(format)
.withLocale(Locale.ENGLISH)
.withOffsetParsed();
DateTime dateTime = DateTime.parse(time, dateTimeFormatter);
System.out.println(dateTime);
Output:
2019-08-29T17:46:11.000+05:30
- In the format pattern string
- You need
EEE
for day of week.d
is for day of month. - You need lowercase
dd
for day of month; uppercaseDD
is for day of year - I have put in
ZZ
because according to the docs this is for offset with a colon;Z
works in practice too
- You need
- Since Thu and Aug are in English, you need an English speaking locale. Since I believe your string comes from
Date.toString()
originally, which always produces English, I foundLocale.ROOT
appropriate. - I found it better to parse into a
DateTIme
. To preserve the offset from the string we need to specify that throughwithOffsetParsed()
(you can always convert toLocalDateTime
later if desired).
Links
- Joda-Time home page
- Related question: Joda Time parse a date with timezone and retain that timezone
- Documentation of
org.joda.time.format.DateTimeFormat
with the format pattern letters including their case