Tuesday, December 11, 2007

Is Sun's developer over smart or just stupid?

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?

1 comment:

Kevin A. Roll said...

DateFormat.setLenient(false);