Home Java Java-conversion Convert String into date

Related Tutorials


 
 

Share on Google+Share on Google+

Convert String into date

Advertisement
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. 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

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 20, 2013

Related Tutorials

Discuss: Convert String into date  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com