I want to convert string to date format, but the following way didn\'t work.
It yields null
for birth
.
Your code works fine. If you care to use Joda Time you can use this. You can go through the documentation to unleash the complete functionality in case you plan to use the time for DB testing and stuff.
import org.joda.time.DateTime;
DateTime dt = new DateTime("YYYY-MM-DD");//new DateTime("2012-03-30")
System.out.println(dt);
Your answer is right on the money. I put it in a full program and tested it.
It now prints out
Default date format Fri Mar 30 00:00:00 CDT 2012
Our SimpleDateFormat 30-Mar-2012
Our SimpleDateFormat with all uppercase 30-MAR-2012
Here are some tips:
-
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BirthDate {
public static void main(String[] args) {
Date birth = null;
String birthDate = "30-MAR-2012";
DateFormat formatter = null;
try {
formatter = new SimpleDateFormat("dd-MMM-yyyy");
birth = (Date) formatter.parse(birthDate); // birtDate is a string
}
catch (ParseException e) {
System.out.println("Exception :" + e);
}
if (birth == null) {
System.out.println("Birth object is still null.");
} else {
System.out.println("Default date format " + birth);
System.out.println("Our SimpleDateFormat " + formatter.format(birth));
System.out.println("Our SimpleDateFormat with all uppercase " + formatter.format(birth).toUpperCase());
}
}
}