There are two issues with what you're currently trying to do:
- You have a typo in the second line of code which means your
months are being parsed as minutes
- As mentioned, you're not taking into account timezone.
To address the first problem, you need to change
Date d2 = new SimpleDateFormat("dd/mm/yyyy").parse(arr[10]);
to
Date d2 = new SimpleDateFormat("dd/MM/yyyy").parse(arr[10]);
Date formats are case sensitive, what you were trying to do is to parse the month as a **m**inute instead of a **M**onth. In the test I ran, that meant the months were all coming out as January, which I can see was happening in your example as well. Also, I notice that your first line of code, the formatter (which IS set up correctly) is not used.
The second problem is that yes, Java Dates don't behave the way you expect. They MUST have a time component, even though you don't care about it for simply the date. In addition, they must have a timezone since they have a time.
You might not have the choice of moving to the superior Joda library, in which case there are ways to work around this. I've written a test which should demonstrate this:
@Test
public void shouldParseDateCorrectly() throws Exception {
// Given
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
// When
Date parsedDate = format.parse("21/08/2012");
// Then
Assert.assertThat(parsedDate.toString(), is("Tue Aug 21 02:00:00 CEST 2012"));
Assert.assertThat(parsedDate.toGMTString(), is("21 Aug 2012 00:00:00 GMT"));
}
So you can see that I've used the correct format, but also set its timezone to UTC (so it has an offset of zero and no daylight savings). Then when you parse the date with this formatter, the date will come out with a time that's midnight in the UTC timezone. Because my computer is in Europe, when I print this date it shows a time of 2am, because this timezone is 2 hours ahead of UTC. But when I use the deprecated toGMTString method, the time comes out as zero.
When you store this date into MongoDB using the Java driver, it will save the date, the time and the timezone with it, even if all you care about is the date. What you'll need to do when you read the dates back out again is to remember they're in UTC and set the timezone appropriately.
Alternatively, you can store them in MongoDB without changing the timezone, provided you'll always read them in and write them out in the same timezone. But this is fraught with unexpected bugs when a) dealing with times over midnight and b) daylight savings time kicks in (or stops).
Or just use Joda-Time.