1

How do I parse a string like "Fri Feb 14 09:58:21 EST 2020" into a Date in Java ?

The closest example I can find is :

SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";

try {

    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));

}
catch (ParseException e) {
    e.printStackTrace();
}

But it doesn't have the " EST " part, what's the right way to do it ?

8
  • 1
    or here stackoverflow.com/questions/4216745/… Commented Feb 14, 2020 at 15:02
  • 2
    If you are learning how to parse a datetime String, then learn the modern way: java.time Commented Feb 14, 2020 at 15:05
  • 2
    @cricket_007, I'm trying to find the fastest way to the correct answer, I've done date parsing before, just not this one, I can spend hours on it going through the doc's, or do more search, I just don't want to waste too much time on this, that's why I post it here to hope 3 minutes of my time here is worth few hours searching on my own, if you want to know what I've been DOING in the 20 years of Java programming, here are some info : nmjava.com/links.html and here : gatecybertech.com Commented Feb 14, 2020 at 15:37
  • 1
    This is not a place for advertisement. Java date parsing is well covered already and you could get the result in a 1mn research or 3mn reading the doc. Anyway, question is closed Commented Feb 14, 2020 at 15:38
  • 1
    I respect you experience @Frank :) Commented Feb 14, 2020 at 15:55

1 Answer 1

4

Your pattern is not correct, it contain many problems :

  • EEEE replace with EEE
  • , remove this because your string not have comma
  • , same thing for the second comma
  • replace the position of yyyy and put in the end
  • a remove as it is not used at all, and instead use z to match ETC

If you are using java-time you can parse your date using this pattern EEE MMM dd HH:mm:ss z yyyy :

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
        "EEE MMM dd HH:mm:ss z yyyy", 
        Locale.US);
ZonedDateTime zdt = ZonedDateTime.parse(str, formatter);
Sign up to request clarification or add additional context in comments.

3 Comments

This is the modern way... You could mention EST to be automatically converted to -05:00[America/New_York] when using a DateTImeFormatter.ISO_ZONED_DATE_TIME in the format() method.
@deHaar sorry I don't get you
I parsed it like you did and then formatted it with a DateTimeFormatter.ISO_ZONED_DATE_TIME which then outputs 2020-02-14T09:58:21-05:00[America/New_York], but EST isn't only New York time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.