tl;dr
FYI, the Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See Tutorial by Oracle.
OffsetDateTime.parse(
"Thu Aug 29 17:46:11 GMT+05:30 2019" ,
DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss OOOO uuuu").withLocale( Locale.US )
)
.toString()
2019-08-29T17:46:11+05:30
LocalDateTime
cannot represent a moment
"Thu Aug 29 17:46:11 GMT+05:30 2019"
I want to convert to this string to LocalDateTime object.
You cannot.
- The input represents a moment, a specific point on the timeline.
- A
LocalDateTime
cannot represent a moment. A LocalDateTime
has only a date and a time-of-day but lacks the context of a time zone or offset-from-UTC.
Trying to handle your input as a LocalDateTime
would mean discarding valuable information. That would be like handling a amount of money as simply a BigDecimal
while throwing away information about which currency.
OffsetDateTime
You input string includes an offset-from-UTC of five and a half hours ahead. So parse as an OffsetDateTime
object.
Define a custom formatting pattern to match your input, using the DateTimeFormatter
class.
Define
String input = "Thu Aug 29 17:46:11 GMT+05:30 2019" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss OOOO uuuu").withLocale( Locale.US );
OffsetDateTime odt = OffsetDateTime.parse( input , f ) ;
odt.toString(): 2019-08-29T17:46:11+05:30
Tip: That input format is terrible. Educate the publisher of those input string about the standard ISO 8601 for practical date-time formats.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?