2007/12/11

Watch out for java SimpleDateFormat

Look at this code, what it will come out?

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test{
public static void main(String[] args){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = null;
try{
dt = sdf.parse("2000999878-3454555-35344");
System.out.println(sdf.format(dt));
}catch (Exception e){
System.out.println("error");
}
}
}

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;
import java.util.Date;

public class Test{
public static void main(String[] args){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = null;
try{
dt = sdf.parse("2000999878-3454555-35344");
String s = sdf.format(dt);
if(!s.equals("2000999878-3454555-35344"))
System.out.println("Data format wrong!");
}catch (Exception e){
System.out.println("error");
}
}

Ugly codes, but works.

How many online Web systems relying on Java and J2EE have those codes?

5 comments:

Senthil said...

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");
}
}
}

Java Blues said...

Thanks. It works. It's a good tip.

J2EE Blogger said...

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!

Anonymous said...

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.

Anonymous said...

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.

Well well... why another J2EE blog? I benefited from other people's technical blogs, and guess what, it's a good idea to contribute some of my works too. Hope it's helpful and useful, to all of your folks.