Question

I am trying to parse a date with a SimpleDateFormat and I encountered a strange behavior.

This Example prints "Sun Jan 01 19:00:32 CET 2012" on my machine:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class Test {
    public static void main(String[] args) throws ParseException {
        System.out.println(new SimpleDateFormat("MMM dd HH:mm:ss YYYY", Locale.ENGLISH).parse("Sep 26 19:00:32 2012"));
    }
}

I would expect to have "Wed Sep 26 19:00:32 CET 2012" returned instead.

Is my DateFormat String incorrect?

Was it helpful?

Solution

The year uses small caps y:

System.out.println(new SimpleDateFormat("MMM dd HH:mm:ss yyyy", Locale.ENGLISH).
            parse("Sep 26 19:00:32 2012"));

Large cap Y is "Week year" according to javadoc.

OTHER TIPS

Use yyyy (lowercase) instead of YYYY (uppercase). Y is the Week year; whilst y is the year.

Also note that the Y pattern was only introduced in Java 7, which can explain why you are seeing an error. According to the documentation:

If week year 'Y' is specified and the calendar doesn't support any week years, the calendar year ('y') is used instead. The support of week years can be tested with a call to getCalendar().isWeekDateSupported().

Using Java 7, and with a GregorianCalendar, your code works just fine, as you can see in this demo.

the problem is with date parsing not formatting. Try passing new Date() in the parse, see the result and change format accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top