Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How parse date in Java ? some confusion on date formats

I have working with twitter and getting tweets using API and I am using twitter4j library for that. In that I got tweeted date as "Thu Feb 26 00:16:19 EST 2015" and this is a date string. How can I parse this date string to a Date object.

like image 588
ranjith Avatar asked May 15 '26 08:05

ranjith


1 Answers

Java 7 or below:

If you use Java 7 or below then you can parse date like that (more information about date time formatting 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 like that with with a new API:

To convert parsed date/time into a 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 keep time zone information from 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);
}

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

Also, note that the key difference between old SimpleDateFormat and a new java 8 DateTimeFormatter is that SimpleDateFormat is not thread-safe. That means that you cannot use the same formatter instance across multiple parallel threads. However a new DateTimeFormatter is thread-safe.

like image 74
Igor Uzhviev Avatar answered May 16 '26 22:05

Igor Uzhviev