4 Replies Latest reply: Nov 17, 2009 10:29 AM by Tolls RSS

    a problem with parsing a string with SimpleDateFormat

    807580
      I have the following date format : MMMdyyyy. When parsing the string Nov12009 everything is ok and the correct date is produced. But when I try
      to parse the string : Nov212009 then the produces date has : Day = 2 Year = 12009 (!). My question is how can I solve this ambiguity ?. (I cannot change the date presenstation in the given string). What I do not understand is if I say that the year is 4 characters than why does SimpleDateFormat ignore it and produce a 5 character year ?

      Thanks
        • 1. Re: a problem with parsing a string with SimpleDateFormat
          807580
          Because you told it the day field is only one char and it has to handle the extra character somehow. It chose to treat it as an extended year. You could set lenient to false.

          A cludge - if the number of decimal chars in not 5 then insert a zero into the string after the third char. Change the format to "MMMddyyyy".

          Edited by: sabre150 on Nov 17, 2009 8:49 AM
          • 2. Re: a problem with parsing a string with SimpleDateFormat
            807580
            Thx for the reply. You second solution should work. The problem is that the date format might be changed in configuration and it will not always be MMMddyyyy so I cannot treat this as a special case. I do not understand why the 4 character year is ignored and not strict even if setting lienient to false
            • 3. Re: a problem with parsing a string with SimpleDateFormat
              807580
              Javaist wrote:
              Thx for the reply. You second solution should work.
              Not should - will!
              The problem is that the date format might be changed in configuration and it will not always be MMMddyyyy so I cannot treat this as a special case.
              I don't understand. Your parsing is already a 'special case'. By using a regular expression this can be implemented all in one line and it would not be difficult to make the regular expression cover even more 'special cases'.
              I do not understand why the 4 character year is ignored and not strict even if setting lienient to false
              Maybe because it is still too lenient. The designer of the class cannot be expected to cover every conceivable format.
              • 4. Re: a problem with parsing a string with SimpleDateFormat
                Tolls
                The misconception everyone seems to have is that yyyy means 4-character year. It doesn't. It means "take this literally", that is you are saying that what is presented is the actual year. And since any integer is a valid year (bar zero, strictly speaking), then any number is valid.

                yy on the other hand means "truncate to two digits, if need be".