2

I want to convert a Date to a String but I have some problems. My code is this:

SimpleDateFormat formato = new SimpleDateFormat(
            "EEE MMM dd HH:mm:ss z yyyy");

    String hacer = "Fri Nov 01 10:30:02 PDT 2013";
    Date test = null;
    test = formato.parse( hacer);
    System.out.println("prueba===>" + test);

But nothing something is wrong eclipse shows me this error:

Unparseable date: "Fri Nov 01 10:30:02 PDT 2013"
at java.text.DateFormat.parse(Unknown Source)

some help?

V G
  • 18,822
  • 6
  • 51
  • 89
Chris
  • 43
  • 1
  • 5

1 Answers1

5

Probably your default locale doesn't support English months in MMM. For example in Poland MMM supports "styczeń" but not "Jan" or "January"

To change this In SimpleDateFormat you need to set locale which supports months written in English, for example

new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • thanks, adding Locale.ENGLISH works, what is the difference? why not works before putting that? – Chris Nov 01 '13 at 17:27
  • @Chris: It affects how to parse the date. You can check which one is your default with `System.out.println(Locale.getDefault());`. – Keppil Nov 01 '13 at 17:30
  • Probably your default locale doesn't support English months in `MMM`. For example I live in Poland and MMM supports `"styczeń"` but not `"Jan"` or `"January"`. – Pshemo Nov 01 '13 at 17:30
  • actually I try with: System.out.println(Locale.getDefault()); and my default locale not supports English, but now works whit Locale.ENGLISH – Chris Nov 01 '13 at 17:37
  • @Chris Then your problem is solved. Also if you don't want to pass each time `Locale.ENGLISH` in `SimpleDateFormat` constructor you can set your global locale to ENGLISH with `Locale.setDefault(Locale.ENGLISH);` before you use `new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");` – Pshemo Nov 01 '13 at 17:42
  • 1
    Setting the global locale is usually not recommended; it's fighting against the _user's_ system configuration. If you really need to do the parsing in a specific locale, write it explicitly. – Donal Fellows Nov 03 '13 at 17:38
  • @DonalFellows Yes that is true thanks for pointing that. I agree and that is why I just mentioned it in comment as additional info and didn't include it in answer to not encourage others to use this way. With your comment it is more obvious. +1. – Pshemo Nov 03 '13 at 17:44