String to Date Java


After converting Date to String, let us see the other way of converting String to Date.

The same java.text.SimpleDateFormat class used in Date to String is used here.

Following code on String to Date explains.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class StringDate
{
  public static void main(String args[])
  {
    try
    {                          // take input from the user, say 12/06/2013
      String stringDate = "12/06/2013";
      SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
      Date today = sdf1.parse(stringDate);
      System.out.println(today);
    }
    catch(ParseException e)
    {
      System.out.println(e.getMessage());
    }
  }
}

String to Date

In Date to String conversion, we used format() method of SimpleDateFormat. Now it is parse() method.

String stringDate = “12/06/2013”;
SimpleDateFormat sdf1 = new SimpleDateFormat(“dd/MM/yyyy”);
Date today = sdf1.parse(stringDate);

The date is available in string form as stringDate. Create a SimpleDateFormat object, sdf1, while passing the date format "dd/MM/yyyy" as parameter. Use parse() method of SimpleDateFormat and pass the string date object as parameter. The parse method parses string date into java.util.Date object.

See the output screen of String to Date. The date object prints including minutes and seconds etc. which we may do not require. Use getDate(), getMonth() and getYear() methods of Date class to extract the information you require from Date object.

Leave a Comment

Your email address will not be published.