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:
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
Steps to convert String to Date:
- Declare a SimpleDateFormat object. with argument as the format of date eg:- dd/mm/yyyy
- 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
- the input string should not be null or any invalid data.
- It throws ParseException, try to handle it.
No comments:
Post a Comment