Code Snippets: Parsing a String into a Java Date Object

If a beginner coder you may get confused by the fact that Date.parse function has been deprecated. Not to worry though, it was deprecated for good reason as the DateFormat classes gives you a better way to convert strings into JAVA Date objects.

The DateFormat class contains a parse method that will convert a String into a Date Object based on the format you have specified. This gives you the flexibility to convert date Strings that are in various formats.

How to convert a String to a Date

Import the required classes

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
imoprt java.util.Date;

Create your DateFormat initialized with the format of the string you are to convert into a Date object.

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

Convert your date String, but remember to catch the ParseException that can be thrown if the String can not be converted into a Date.

try {
    Date theDate = dateFormat.parse( "09/09/2009" );
} catch (ParseException e ) {
    e.printStackTrace();
}

Resources:

// Code Snippets // Java //

Comments & Questions

Add Your Comment