Convert String into date

In this example we are going to convert String into date. SimpleDateFormat is a concrete class for formatting the dates which is inside package "java.text.*" which have a date format which convert a string into Date format.

Convert String into date

In this example we are going to convert String into date. SimpleDateFormat is a concrete class for formatting the dates which is inside package "java.text.*" which have a date format which convert a string into Date format.

Convert String into date

Convert String into date

In this example we are going to convert String into date. SimpleDateFormat is a concrete class for formatting the dates which is inside package "java.text.* "  which have a date format which convert a string into Date format. It also provide some of the methods like getTimeInstance, getDateInstance or getDateTimeInstance in date format and each of these methods return the date/time with default format pattern. SimpleDateFormat take string as input an convert that string into Date format. Here are the step as follows.

  • Create a SimpleDateFormat object with a date pattern e.g. dd-MM-yyyy. here d denotes day of month, M is for month of year and yyyy is year in four digit e.g. 2013.
  • Call parse() method of SimpleDateFormat and the result into Date object and parse() method of SimpleDateFormat throws ParseException so you need to either throw it or you can provide handling of this exception. Let?s see the example of converting string to date in java.

Example:  Code to convert String to Date in java.

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

public class Stringtodate
  {
   public static void main(String args[]) 
   {
	
    DateFormat df=new SimpleDateFormat("DD/MM/yyyy"); 
    DateFormat format = null;
    Date convertedDate = null;
  try {
		 

        //convert string to date with ddMMyyyy format example "20052013"
        String ddMMyyyy = "20052013";
        format = new SimpleDateFormat("ddMMyyyy");
        convertedDate = (Date) format.parse(ddMMyyyy);
        System.out.println("Date from ddMMyyyy String in Java : " + convertedDate);
       
       } catch (ParseException e)
	{
		
		e.printStackTrace();
	}
      }
  }

Output :  After compiling and executing the above program.

Download SourceCode