The following Java code just parses a date (with time portion) 2009-01-28-09:11:12 using SimpleDateFormat. Let’s have look at it.
final public class Main
{
public static void main(String[] args)
{
try
{
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date d = df.parse("2009-01-28-09:11:12");
System.out.println(d);
}
catch (ParseException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The date (with time) displayed (after parsing) by the above code is as follows,
Sun Nov 30 22:07:51 IST 2008
even though we are attempting to parse the date 2009-01-28-09:11:12. It looks somewhat wonky. Why does it parse so?
Shouldn’t your date format be something like this:
to match this format:
?
As for why, per this:
the parser actually looks at these as numbers, and the trick is that – is a part of a number, representing negative numbers. So if you do:
it gives:
That parses 2009 as yyyy, then -0 as MM (which is previous month as months start from 1), then 1 as dd, etc.
As per parse in DateFormat:
I guess, if you have an option, it would be better to use slashes instead of dashes, if you like formats like 2009/01/02 12:34:56. This:
will throw an exception:
I can only conclude it’s a very good thing that
/is not considered a number division by DateFormat…