tags:

views:

694

answers:

1

I came across a code snippet like this:

Timestamp expiryDate = Timestamp.valueOf(dateStr + " " + "23:59:59.000");

Here dateStr is a string entered by the user in a form, in the format yyyy-mm-dd. Now the behavior of Timestamp.valueOf is such that it converts non-existent dates into appropriate proper dates. Say 31st June 2008 into 01st July 2008.

How can I check in Java if the dateStr string is in fact a valid date ? I know I can manually do the check, but what I would like to know is whether any method is already available to do the same.

+5  A: 

Try SimpleDateFormat. You simply set a format such as the one in your example and then call parse on your dateStr.

AdamC
You must make sure that setLenient() is set to false, otherwise you wind up with the same issues as Timestamp.
Spencer K
Thanks Adam. It worked fine but not before calling the setLenient(false) on the SimpleDateFormat object. Thanks for that pointer, Spencer !
Vijay Dev
Also, be advised that SimpleDateFormat.parse() is *not* Thread-safe. So if you're doing this in say a servlet, you cannot have a static instance of your SimpleDateFormat, and will have to manage it accordingly.
Spencer K