Look at this code, what it will come out?
import java.text.SimpleDateFormat; public class Test{ |
The result is:
247625706-07-03 |
Is this what you expected? You thought it would have thrown an exception of invalid format of text you passed in.
It's very common for a developer do date and time data conversion from text and vice versa in different format. Will it breach your boundary validation if you purely rely on this stupid SimpleDateFormat class?
Work around so far like:
import java.text.SimpleDateFormat; public class Test{ |
Ugly codes, but works.
How many online Web systems relying on Java and J2EE have those codes?
5 comments:
Hi,
SimpleDateFormat provides a method for checking the strict date & date format.
Method name setLenient().
Go through the below example. This is correct way to do.
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = null;
try{
sdf.setLenient(false);
dt = sdf.parse("2000999878-3454555-35344");
System.out.println(sdf.format(dt));
}catch (Exception e){
System.out.println("error");
}
}
}
Thanks. It works. It's a good tip.
After all the setLenient method doesn't work so well. Try parse something like "2009-04-21BLAH" and it succeeded.
We're back to the solution described in the post!
J2EE Blogger:
It will work because the parse method is supposed to match the beginning of the string for as many characters as are needed to deal with the pattern. Lenient vs Strict only determines behavior when something like 'Jan 32 2009' is presented; lenient will get you Feb 01 2009; strict will throw.
But in your example, the 'BLAH' comes after character 10, which are all that are needed to satisfy the format.
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
df.setLenient(false);
Date x = df.parse("01.01.197i");
will not throw an Exception but should throw it.
Post a Comment