tl;dr
String input = "Fri, 13 Apr 2018 02:26:19 -0700 (PDT)" ;
…
java.util.Date.from( // Convert from modern classes `OffsetDateTime` & `Instant` to troublesome legacy class `Date`. Do so only if absolutely necessary.
OffsetDateTime.parse(
input.substring( 0 , input.indexOf( " (" ) ) , // Drop the ambiguity-prone pseudo-zone ` (PDT)` from the end.
DateTimeFormatter.RFC_1123_DATE_TIME // Parse using a built-in formatter defined for RFC 1123 strings.
)
.toInstant() // Extract UTC value (`Instant`) from `OffsetDateTime`.
) // Returns a legacy `java.util.Date` object.
DateTimeFormatter.RFC_1123_DATE_TIME
As discussed in the Answer by GPI, Java provides a formatter for this format defined in RFC 1123 (see also RFC 822).
Except that pseudo-time-zone codes such as PDT
cannot be parsed unambiguously as they are not standardized and are not unique. So strip that off.
String original = "Fri, 13 Apr 2018 02:26:19 -0700 (PDT)";
// Delete non-standard pseudo-zone at end.
String input = original;
if ( input.endsWith( ")" ) ) {
int index = input.indexOf( " (" );
input = input.substring( 0 , index );
}
DateTimeFormatter f = DateTimeFormatter.RFC_1123_DATE_TIME;
OffsetDateTime odt = OffsetDateTime.parse( input , f );
Dump to console.
System.out.println( original );
System.out.println( input );
System.out.println( odt );
Fri, 13 Apr 2018 02:26:19 -0700 (PDT)
Fri, 13 Apr 2018 02:26:19 -0700
2018-04-13T02:26:19-07:00
Convert
How can I convert this into a Java.util.Date format?
Don’t. The java.util.Date
is a poorly-designed, confusing, and troublesome. Avoid it.
But if you must interoperate with old code not yet updated to java.time classes, you can convert back and forth. Call new methods added to the old classes.
Extract a Instant
from OffsetDateTime
, as that class replaces java.util.Date
to represent a moment in UTC.
Instant instant = odt.toInstant() ;
java.util.Date d = java.util.Date.from( instant ) ;
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
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.