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?

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.