java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Do not use a fixed text for the timezone:
Do not use a fixed text (e.g. 'UTC'
) for the timezone because that approach may fail for other locales.
Solution using java.time
, the 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 = "Sat Nov 01 20:08:07 UTC 2014";
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:
2014-11-01T20:08:07Z[Etc/UTC]
ONLINE DEMO
For any reason, if you need to convert this object of ZonedDateTime
to an object of java.util.Date
, you can do so as follows:
Date date = Date.from(zdt.toInstant());
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness
Just for the sake of completeness, I have written the following solution using Joda Date-Time API:
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strDateTime = "Sat Nov 01 20:08:07 UTC 2014";
DateTimeFormatter dtf = DateTimeFormat.forPattern("E MMM d H:m:s z y").withLocale(Locale.ENGLISH);
DateTime dt = dtf.parseDateTime(strDateTime);
System.out.println(dt);
}
}
Output:
2014-11-01T20:08:07.000Z
* 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.