java.time
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time
, the modern date-time API*.
Another important thing to note is that your string has English
text and therefore you must use Locale.ENGLISH
so that you do not get an exception or some wrong result when your code is run on a JVM whose Locale
is not English
. Anyway, NEVER use a date-time parsing/formatting type (e.g. SimpleDateFormat
, DateTimeFormatter
etc.) without Locale
because these types are Locale
-sensitive.
Demo using modern date-time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
String strDateTime = "Fri Aug 12 16:08:41 EDT 2011";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E MMM d H:m:s z u", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
2011-08-12T16:08:41-04:00[America/New_York]
If at all, you need a java.util.Date
object, you can obtain it as follows:
Date date = Date.from(zdt.toInstant());
Learn more about the modern date-time API from Trail: Date Time.
Using the legacy API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String args[]) throws ParseException {
String strDateTime = "Fri Aug 12 16:08:41 EDT 2011";
SimpleDateFormat sdf = new SimpleDateFormat("E MMM d H:m:s z y", Locale.ENGLISH);
Date date = sdf.parse(strDateTime);
// ...
}
}
Note that the java.util.Date
object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT
(or UTC). When you print an object of java.util.Date
, its toString
method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat
and obtain the formatted string from it.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.