-2

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,

RaymondMachira
  • 344
  • 2
  • 5
  • 14
  • 5
    Are you using `y` or `Y`? –  Apr 08 '13 at 19:48
  • 1
    The exception message doesn't match with your code. And obviously, 12.1.5 doesn't match with yyyy.MM.dd. Post the real code, and the real exception message, or figure it out by yourself, because it should be obvious. – JB Nizet Apr 08 '13 at 19:50
  • 2
    Good: `String pattern = "yyyy.MM.dd";` (lower-case "yyyy"). Q: `Illegal pattern character 'Y'` (upper case "Y"). Q: Are you sure you're posting the exact code and the exact error message? – paulsm4 Apr 08 '13 at 19:51
  • @JB Nizet, AFAIK, either "2013" or "13" should be valid input for a year mask of "yyyy": http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – paulsm4 Apr 08 '13 at 19:52
  • Thank you everyone. 1, I am using `y`, not `Y`. I have also tried using **4digits year, 2month and 2day**- in line with my SDF. The code as posted here was as I was tinkering around. But that too failed.@JB Nizet @0A0D – RaymondMachira Apr 08 '13 at 21:39

1 Answers1

5

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...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194