Java – How to parse dates in Java? The date format is somewhat confusing

How to parse dates in Java? The date format is somewhat confusing… here is a solution to the problem.

How to parse dates in Java? The date format is somewhat confusing

I’ve been using Twitter and using the API to get tweets, for which I’m using the twitter4j library.
There, I received a tweet dated “Thu Feb 26 00:16:19 EST 2015“, which is a date string. How to parse this date string into a Date object.

Solution

Java 7 or below:

If you are using Java 7 or earlier, you can parse dates like this (for more information on the datetime format, click here .) http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html):

public static Date java7() throws ParseException {
    String dateAsString = "Thu Feb 26 00:16:19 EST 2015";

DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    return df.parse(dateAsString);
}

Java 8:

Java 8 has a new date/time API (java.time), so you can parse using the new API:

Convert resolved date/time to local time zone (current computer time zone):

public static LocalDateTime java8() {
    String dateAsString = "Thu Feb 26 00:16:19 EST 2015";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy");
    return LocalDateTime.parse(dateAsString, formatter);
}

If you need to preserve the time zone information in the original string, use ZonedDateTime instead of LocalDateTime:

public static ZonedDateTime java8Zoned() {
    String dateAsString = "Thu Feb 26 00:16:19 EST 2015";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy");
    return ZonedDateTime.parse(dateAsString, formatter);
}

For more information about the date/time format in the java.time API: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Also note that the main difference between the old SimpleDateFormat and the new Java 8 DateTimeFormatter is that SimpleDateFormat is not thread-safe. This means that you cannot use the same formatter instance in multiple parallel threads. However, the new DateTimeFormatter is thread-safe.

Related Problems and Solutions