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.

- 4,526
- 5
- 27
- 31
-
1`DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); Date startDate = df.parse(startDateString);` - more on this [here](http://stackoverflow.com/questions/6510724/how-to-convert-java-string-to-date-object) – Skynet Feb 26 '15 at 06:05
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.

- 308
- 1
- 4