This is quite a common query which is faced by a Java Programmer while dealing with dates. The problem is when a form value returns back the date value input by the user in the form of a string. The application might be using a Date object to hold the date values in the application.

So in order to convert the String date value to Date object you might be tempted to use the simplified conversion format which is,

String str = "26/08/1994";
Date date = new Date(str);

But the problem with the above step is that the Date() constructor is now deprecated in JDK1.5 onwards and hence won’t be a good practice to use the deprecated ones.

So the solution for this is to use the SimpleDateFormat object is,

String str = "26/08/1994";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //please notice the capital M
Date date = formatter.parse(str);

The SimpleDateFormat object function parse() helps to parse the string value of the date to the desired value with the help of the customization syntax provided while instantiating the SimpleDateFormat object. The parsed values are then fed to the Date object instead of passing through the constructor as done earlier.

Convert Date back to String
To print back the date in the desired format we again require the same object i.e SimpleDateFormat to format according to our requirements. So to print we would do the following,

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Date is : " + formatter.format(date)); //using the date object from earlier

Notice that here we use the format() function and not the parse() function since the format() function takes in a parameter of Date type while parse() takes in a String parameter.

Its easier to remember this way,
– String parse() to Date to use in the application
– Date format() to String to produce the display string


Stumble Digg Technorati Subscribe Delicious