How to convert String to Date

In this post we will see how to convert String to date in java. For this we will use SimpleDateFormat API to convert string to date.

We need to pass in the dateformat in which we want to convert String to date as a parameter to the constructor of SimpleDateFormat

Then using the SimpleDateFormat.parse(String) method we convert the String into our desired date.

While using the SimpleDateFormat.parse(String) method, we need to wrap it in try-catch block as their is a possibility of getting a ParseException due to invalid format/String passed.

Important:

Please note that the date format that we give is case sensitive
for example :
M – Month in year
m – Minute in hour
D – Day in year
d – Day in month
You can get the full details about the format here – http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Code Sample – Convert String to Date

Output

Reference

SimpleDateFormat API