Convert a String to Date in Java
Description
The following code shows how to convert a String to Date.
Example
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/* w ww .j a v a 2s . c o m*/
public class Main {
public static void main(String[] args) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date theDate = dateFormat.parse("01/01/2009");
System.out.println(dateFormat.format(theDate));
System.out.println(isValidDate("2004-02-29"));
System.out.println(isValidDate("2005-02-29"));
}
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
}
The code above generates the following result.