Monday, January 9, 2012

Java Version Conflicts

import java.sql.Date;

public class Main
{
             public static void main(String[] args)
            {
                        String strDay = "9";
                        String strMonth="1";
                        String strYear = "2012";
                        int dd = 0;
                        int mm = 0;
                        int yyyy = 0;
                        String Currentdate = "";
                        dd = Integer.parseInt(strDay);
                        mm = Integer.parseInt(strMonth);
                        yyyy = Integer.parseInt(strYear);
                        Date date = new Date(0000 - 00 - 00);
                        Currentdate = yyyy + "-" + mm + "-" + dd;
                        date = Date.valueOf(Currentdate);
                        System.out.println(date);
            }
}


The above program works fine with Java 1.6.0.

But throws out exception,

Exception in thread "Thread-1" java.lang.IllegalArgumentException
        at java.sql.Date.valueOf(Date.java:138)

in my client's PC who have installed Java 1.6.24 in his Ubuntu PC.


We found that the issue was with the Java versions installed in PC's.

java.sql.Date package handles date in String.valueOf in the format yyyy-mm-dd(eg:- 2012-01-09) in newer version whereas it can handle data in the format 2012-1-9 in older version.

For new java version to handle this issue, modify the program to

import java.sql.Date;

public class Main
{
             public static void main(String[] args)
            {
                        String strDay = "9";
                        String strMonth="1";
                        String strYear = "2012";
                        int dd = 0;
                        int mm = 0;
                        int yyyy = 0;
                        String Currentdate = "";
                        dd = Integer.parseInt(strDay);
                        mm = Integer.parseInt(strMonth);
                        yyyy = Integer.parseInt(strYear);
                        Date date = new Date(0000 - 00 - 00);
                        Currentdate = yyyy + "-" + String.format("%02d",mm) + "-" + String.format("%02d",dd);
                        date = Date.valueOf(Currentdate);
                        System.out.println(date);
            }
}