Convert a String to a Date in Java

This Java tutorial shows how to convert a String representation of a date into a Date object.

To convert a String representation of date, we will use the SimpleDateFormat class (java.text package). The SimpleDateFormat class will allow us to specify the format of the string that will be converted.

For this example, the following format will be used "MM/dd/yyyy". This specifies a 2 digit month, a 2 digit day, and a 4 digit year. For a complete listing of date format characters, refer to the SimpleDateFormat class documentation.

The final step of converting the String into a date is to pass the String into the parse() method of SimpleDateFormat. This method will convert the String to a date based on the patter supplied to the constructor of SimpleDateFormat.

The following code example puts it all together to show how to convert a String to a Date.

import java.util.Date;
import java.text.SimpleDateFormat;

...

String dateStr = "05/30/2009";

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

Date date = dateFormat.parse(dateStr);


0 comments:

Post a Comment