Java Simple Date Format [duplicate]

2019-09-21 16:44发布

问题:

This question already has an answer here:

  • Illegal pattern character 'Y' on Ubuntu 2 answers

I am trying to format text into a date. Here is what I have:

String pattern = "yyyy.MM.dd";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date d=sdf.parse("12.1.5");

I get:

java.lang.IllegalArgumentException: Illegal pattern character 'Y'

at this point.

I have also tried using a ParsePosition as well as "2012.01.05". Same error.

How can I parse this string into a date? Any optional ways? What am I missing?

Thanks,

回答1:

The code you've given works fine - although the fact that you're claiming you'll have a 4 digit year, 2 digit month and then 2 digit day, and then providing 2-1-1 is pretty ropy.

Given the exception you're getting, I suspect that your pattern is actually "YYYY.MM.dd" instead. That's valid in Java 7 where Y means "week year" but it's not valid in Java 6 which doesn't support Y as a format specifier - only y.

Even when it's valid, you really don't want Y here - you would only specify week years when you're also specifying the week-of-week-year and day-of-week, which you're not doing here.

Stick to the pattern you've actually got in the code you posted - but make sure your data actually matches it...