Reputation: 1066
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?
Upvotes: 2
Views: 2175
Reputation: 91379
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.
Upvotes: 2
Reputation: 2036
the problem is with date parsing not formatting. Try passing new Date() in the parse, see the result and change format accordingly.
Upvotes: 0
Reputation: 328923
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.
Upvotes: 10