Parse String to Date in Java

Another post explains how to create a Date instance in Java. But if you have a string and want to convert it to a Date, you go about it a completely different way (yes, you may be able to hear a hint of sarcasm in my voice). :) Below is a “simple” solution. You can get more advanced with the format string you use, etc.

public static Date ParseDate(String dateString)
{
    return ParseDate(dateString, "MM/dd/yyyy");
}
 
public static Date ParseDate(String dateString, String datePattern)
{
    try
    {
        SimpleDateFormat fmt = new SimpleDateFormat(datePattern);
        return fmt.parse(dateString);
    }
    catch (Exception ex)
    {
        return null;
    }
}

You would call it this way:

Date date1 = ParseDate("01/02/2008");
Date date2 = ParseDate("2008-01-02", "yyyy-MM-dd");

Leave a Reply