, , ,

Recently, when looking at a bug related to Timestamp, I found out that the valueOf() method in java.sql.Timestamp works differently in JDK 6 than the earlier versions.

Timestamp.valueOf(), when provided with a timestamp which contains a date or a month with a single digit. eg. 2009-9-20, 2009-9-3, 2009-12-4 etc., behaves differently in JDK 6 – it throws an IllegalArgumentException saying that the timestamp is not properly formatted. Whereas JDK 5 (and earlier versions) works just fine providing the proper values with ‘0’ prefixed to those single digit numbers. However JDK 6 is fine with hours, minutes, seconds being single digits. As usual, got curious and started exploring why this happens by looking at the source code for the Timestamp class in JDK 5 and 6.

Here’s the JDK 6 Timestamp.valueOf() snippet:

int counterD = 0;
int intDate[] = {4,2,2};

int counterT = 0;
int intTime[] = {2,2,12};

while(stringTokeninzerDate.hasMoreTokens()) {
String tokenDate = stringTokeninzerDate.nextToken();
if(tokenDate.length() != intDate[counterD] ) {
throw new java.lang.IllegalArgumentException(formatError);

//Commenting this portion out for checking of time

while(stringTokeninzerTime.hasMoreTokens()) {
String tokenTime = stringTokeninzerTime.nextToken();

if (counterT < 2 && tokenTime.length() != intTime[counterT] ) {
throw new java.lang.IllegalArgumentException(formatError);

The code in bold shows that there is a strict check on the length of the digits that constitute the datepart of the timestamp. The commented out source is the reason why the format of the digits in the time part is not strictly enforced.

I thought it’s good to dig more into this and asked in Stack Overflow and people helped out in identifying more details: The behaviour is already filed as a bug and more info about the bug was found here. A workaround for this problem is available here.