There are two problems with your code:
- You have used
Y
(which specifies Week year) instead of y
(which specifies Year). Check the documentation to learn more about symbols. Learn more about it here.
- Your date-time string is in English and therefore your code won't work in an expected manner if you run it on a JVM with non-English
Locale
. Date-time parsing/formatting types are Locale
-sensitive. Learn more about here.
java.time
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Solution using the modern API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEEE, MMMM d, u h:m:s a z", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse("Thursday, July 27, 2006 10:10:02 PM PST", dtf);
System.out.println(zdt);
}
}
Output:
2006-07-27T22:10:02-07:00[America/Los_Angeles]
In case you need to convert this object of ZonedDateTime
to an object of java.util.Date
, you can do so as follows:
java.util.Date date = Date.from(zdt.toInstant());
Learn more about the the modern date-time API* from Trail: Date Time.
Solution 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 {
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM d, y h:m:s a z", Locale.ENGLISH);
Date date = sdf.parse("Thursday, July 27, 2006 10:10:02 PM PST");
//...
}
}
* 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.