Not able to convert string dd/MM/yyyy to Date dd/MM/yyyy in java

I have an input string of the format dd/MM/yyyy, I need to convert it into date dd/MM/yyyy.

My approach is:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String date = formatter.format(formatter.parse("22/09/2016"));
Date convertedDate = formatter.parse(date);

I was expecting 22/09/2016 as a date object, however the format returned was not as expected. O/P=>Mon Sep 12 00:00:00 IST 2016

Any idea where I am going wrong? Thanks in advance!

Jon Skeet
people
quotationmark

You seem to be assuming that a java.util.Date "knows" a format. It doesn't. That's not part of its state - it's just the number of milliseconds since the Unix epoch. (There's no time zone either - the IST you're seeing there is your local time zone; that's just part of what Date.toString() does.)

Basically, a Date is just an instant in time - when you want a particular formatted value, that's when you use SimpleDateFormat.

(Or better, use java.time.*...)

Think of it like a number - the number sixteen is the same number whether you represent it in binary as 10000, decimal as 16, or hex as 0x10. An int value doesn't have any concept of "I'm a binary integer" or "I'm a hex integer" - it's only when you convert it to a string that you need to care about formatting. The exact same thing is true for date/time types.

people

See more on this question at Stackoverflow