tl;dr
OffsetDateTime
.parse
(
"Fri Sep 30 18:31:00 GMT+04:00 2016" ,
DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss O uuuu" , Locale.US )
)
.toString()
2016-09-30T18:31+04:00
Avoid legacy classes
The other Answers are now outmoded. The terrible Date
, Calendar
, and SimpleDateFormat
classes are now legacy, supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
Your input string represents a date with time-of-day in the context of an offset-from-UTC. An offset is a number of hours ahead or behind of the baseline of UTC. For this kind of information, use OffsetDateTime
class.
Note that an offset-from-UTC is not a time zone. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region.
The DateTimeFormatter
class replaces SimpleDateFormat
. The formatting codes are similar, but not exactly the same. So carefully study the Javadoc.
Notice that we pass a Locale
. This specifies the human language and cultural norms to use in parsing the input, such as the name of the month, name of the day-of-week, the punctuation, the capitalization, and so on.
package work.basil.example.datetime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Parsing
{
public static void main ( String[] args )
{
Parsing app = new Parsing();
app.demo();
}
private void demo ( )
{
String input = "Fri Sep 30 18:31:00 GMT+04:00 2016";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss O uuuu" , Locale.US );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
System.out.println( "odt = " + odt );
}
}
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?