Java SimpleDateFormat: How to convert a Java String to a Date

Summary: This is a Java SimpleDateFormat (date formatting) example, showing how to convert a String to a Date.

In an earlier example I showed how to use the Java SimpleDateFormat class to convert from a Date to a String, but you can also use the SimpleDateFormat class to convert in the opposite direction, from a given Java String to a Date object.

SimpleDateFormat: Java String to Date conversion

Here’s the source code for a complete SimpleDateFormat example that demonstrates how to convert from a given formatted Java String to a Date object:

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

/**
  * Java SimpleDateFormat - convert a Java String to a Date
  *
  * Uses a String pattern to define the expected date format.
  *
  */
public class SimpleDateFormatStringToDate
{
  public static void main(String[] args)
  {
    // (1) create a SimpleDateFormat object with the desired format.
    // this is the format/pattern we're expecting to receive.
    String expectedPattern = "MM/dd/yyyy";
    SimpleDateFormat formatter = new SimpleDateFormat(expectedPattern);
    try
    {
      // (2) give the formatter a String that matches the SimpleDateFormat pattern
      String userInput = "09/22/2009";
      Date date = formatter.parse(userInput);

      // (3) prints out "Tue Sep 22 00:00:00 EDT 2009"
      System.out.println(date);
    }
    catch (ParseException e)
    {
      // execution will come here if the String that is given
      // does not match the expected format.
      e.printStackTrace();
    }
  }
}

Discussion

As you can see from that example, the steps to convert from a given Java String to Date using SimpleDateFormat are:

  • Craete a SimpleDateFormat instance, giving it the expected format
  • Attempt to parse a String that is supposed to contain a date in the format we expect
  • If the SimpleDateFormat.parse method can't parse the given String, it will throw a ParseException
  • If the SimpleDateFormat.parse method can parse the given String, it converts the String to a Date object

Again, just to drill this point home, the date format we're expecting ("MM/dd/yyyy") must match the format we're given (as it does in "09/22/2009"), otherwise the parse method will throw a ParseException.

Bonus: Using an array of patterns in a SimpleDateFormat Date to String conversion

Now that you've seen a simple example of how this Java SimpleDateFormat Date to String conversion works, lets take a look at a real world example of how you might convert a Date to a String, using an array (or List) of possible String date formatting patterns.

In this example, I'm showing the source code for a Java method that attempts to parse a given Java String (dateString) against an array of possible Java Date formatting patterns. I think this is a terrific approach, because it lets a user enter a date in a wide range of date formats, and then this method does the hard work of seeing if the date format they entered matches any of the date formats our program can handle.

Given that introduction, here's an example Java method named parseDate that attempts to convert a given Java String to a Date object using a given list of potential custom date formats:

/**
 * @param dateString An input String, presumably from a user or a database table.
 * @param formats An array of date formats that we have allowed for.
 * @return A Date (java.util.Date) reference. The reference will be null if 
 *         we could not match any of the known formats.
 */
public static Date parseDate(String dateString, String[] formats)
{
  Date date = null;
  boolean success = false;

  for (int i = 0; i < formats.length; i++)
  {
    String format = formats[i];
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);

    try
    {
      // parse() will throw an exception if the given dateString doesn't match
      // the current format
      date = dateFormat.parse(dateString);
      success = true;
      break;
    }
    catch(ParseException e)
    {
      // don't do anything. just let the loop continue.
      // we may miss on 99 format attempts, but match on one format,
      // but that's all we need.
    }
  }

  return date;
}

I tried to document this SimpleDateFormat example pretty well, so I don't have anything else to add to it at this time. The important thing to note is that the program will stay in the for loop shown until either (a) the date given (dateString) matches one of the given Java date formatting patterns, or (b) all the patterns have been exhausted, in which case the method returns a null Date reference.

Summary: Java SimpleDateFormat date formatting

I hope you find these Java SimpleDateFormat examples helpful. Programmers constantly need to convert from Java String to Date, or from a Java Date to String, and I find examples are the easiest way to learn. If you have any comments or questions, just fill in the comment form below, and I'll get back with you.