3

I use SimpleDataFormat for years. I never get this Exception

the program is below, I got this code of an example from the internet:

    public static void main(String[] args) {
    // Make a new Date object. It will be initialized to the
    // current time.
    Date now = new Date();

    // Print the result of toString()
    String dateString = now.toString();
    System.out.println(" 1. " + dateString);

    // Make a SimpleDateFormat for toString()'s output. This
    // has short (text) date, a space, short (text) month, a space,
    // 2-digit date, a space, hour (0-23), minute, second, a space,
    // short timezone, a final space, and a long year.
    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

    // See if we can parse the output of Date.toString()
    try {
        Date parsed = format.parse(dateString);
        System.out.println(" 2. " + parsed.toString());
    }
    catch(ParseException pe) {
        System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
    }

    // Print the result of formatting the now Date to see if the result
    // is the same as the output of toString()
    System.out.println(" 3. " + format.format(now));
}

Ok pretty Simple.

The result:

 1. Wed Aug 08 13:49:05 BRT 2012
    ERROR: Cannot parse "Wed Aug 08 13:49:05 BRT 2012"
 3. Qua Ago 08 13:49:05 BRT 2012

You see that the 2. thrown an error? For me it's everything correct.

Is there any locale stuff I should set?

My O.S: Windows 7 Proffesional, Service Pack 1 JDK: jdk1.6.0_25

1
  • Yep, I almost doesn't enter here. I'll do it... Commented Aug 8, 2012 at 17:38

1 Answer 1

9

It looks like it's a locale issue, yes. If you look at the output, it's not using English month and day names - so it wouldn't be able to parse them either. Try specifying English when you create the SimpleDateFormat:

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",
                                               Locale.US);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.