File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Date Formatting. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Date Formatting." Watch "Date Formatting." New topic

Date Formatting.

Arnav Velimala
Ranch Hand

Joined: Jun 04, 2007
Posts: 37

I'm trying to validate a data using SimpleDateFormat. The input is expected to be of the format : "yyyy-MM-dd hh:mm:ss.SSS". Following is the method I used to validate.

Now my question is :
it is returning true even if I give following (invalid??)date formats:
"2008-14-18 05:43:28.09""20-12-2008 05:43:28.7897"
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

Take a look at the DateFormat.html.setLenient(boolean) method. It is set to true by default. As such the parse method may

use heuristics to interpret inputs that do not precisely match this object's format.

If you set this to false your code will does what you expect.

So that the code does not need to create a new DateFormat object each time and incur the cost of parsing the date pattern, you might want to consider making that object an instance variable. Then you only incur the cost of parsing the actual date string and not both the pattern and the date string each time the method is called.
I agree. Here's the link:
subject: Date Formatting.
It's not a secret anymore!