Tuesday, May 31, 2011

Db2 26 Byte Timestamp in Java

I was looking for the db2 Timestamp format for long days and finally got the solution
public static Object getCurrentTimeStamp(int returnType) {
long timeInMillis = System.currentTimeMillis();
long timeInNanos = System.nanoTime();
Timestamp timeStamp = new Timestamp(timeInMillis);
timeStamp.setNanos((int) (timeInNanos % 1000000000));
if (returnType == ReturnType.TIMESTAMP)
return timeStamp;
else {
String db2TimeStamp;
db2TimeStamp = timeStamp.toString().replace(' ', '-');
db2TimeStamp = db2TimeStamp.replace(':', '.');
System.out.println(db2TimeStamp.substring(0, 26));
return db2TimeStamp.substring(0, 26);
}
}

The time in millis does not represent the time in nanos. More precise it simply can't be. You're supposed to use Timestamp#setNanos() to set the real nanos.
java.sql.Timestamp constructor go like this:
public Timestamp(long time) {
super((time/1000)*1000);
nanos = (int)((time%1000) * 1000000);
if (nanos < 0) {
nanos = 1000000000 + nanos;     
super.setTime(((time/1000)-1)*1000);
}
}

It basically accepts time in millisecond and then extracts the last 3 digits and makes it nanos. So for a millisecond value of 1304135631 421, I'm getting Timestamp.getnanos() as 421000000. This is plain calculation (adding 6 zeroes at the end).

No comments:

Post a Comment