tags:

views:

39

answers:

1

The following code causes an "Unparseable date" exception when executed. Is there any way I can tell SimpleDateFormat the date string must ends with 00?

public class Main {
public static void main(String[] args) {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss00");
    try {
        Date date = format.parse("2009030916301600");
    } catch (ParseException ex) {
        System.out.println("Exception" + ex);
    }
}

}

+3  A: 

Use singlequotes to represent literal text.

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss'00'");

See also:


Update: it didn't work here after a quick test. I suspect an uncovered corner case in javadoc. After all, you can just leave them away.

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

Alternatively, you can also use S to represent them as milliseconds. It won't affect the final result since it's zero anyway.

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssS");
BalusC
Tried this before, same error. Javadoc states that any character outside a-z A-Z are not interpreted, so it should work without escaping.
miara
See the updated answer. Remove the `00` or treat them as milliseconds using `S`.
BalusC
But then to be sure there is 00, I must check millis in result date (how?) if it is 0.
miara
Use the one with `S` and check afterwards if `date.getTime() % 1000 == 0`
BalusC
The behaviour is documented: "For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields." So even if you use only "ss" in the pattern, all four remaining digits ("1600") are consumed for the second field. The ParseException is then thrown, since the parser is not able to find the following literal "00", as expected by the pattern.
jarnbjo
@jarn: makes sense, thanks!
BalusC