Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Thursday

How to convert String to Date in Java

How to convert String to Date in Java

Java provides java.text.DateFormat and java.text.SimpleDateFormat for converting String to date and vice versa.

Steps to convert String to Date:


  1. Declare a SimpleDateFormat object. with argument as the format of date eg:- dd/mm/yyyy
  2. Use the parse() method to  covert the string object into its date type.
eg:- 

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

public class dateParsing{
 
    
public static void main(String args[]) throws ParseException{
     
        DateFormat f = 
null;
        Date cD = 
null;

        String d = "14-09-2011";
        f = 
new SimpleDateFormat("dd-MM-yyyy");
        cD = 
(Date) f.parse(d);
        System.
out.println("Coverted String to Date" + cD);
}
}

The main things to remember are

  1. the input string should not be null or any invalid data.
  2. It throws ParseException, try to handle it.

No comments:

Post a Comment