Tom
Tom

Reputation: 962

JAVA new Timestamp() make ending ZERO disappear when time in ms end with ZERO

In my logs I am using : (java.sql.Timestamp)

 new Timestamp(System.currentTimeMillis())

it behaves strangely (IMHO) :

I expected to have : 2017-03-28 17:08:55.960 with an ending 0

Questions :

Is this a normal behavior of new Timestamp() ?

Why the terminating ZERO is being dropped ?

Upvotes: 1

Views: 425

Answers (1)

freedev
freedev

Reputation: 30147

So, yes it is the correct behaviour. Because the implementation of toString() method for the nanoseconds part is:

if (nanos == 0) {
    nanosString = "0";
} else {
    nanosString = Integer.toString(nanos);
    ...
}

In the else part:

// Truncate trailing zeros
char[] nanosChar = new char[nanosString.length()];
nanosString.getChars(0, nanosString.length(), nanosChar, 0);
int truncIndex = 8;
while (nanosChar[truncIndex] == '0') {
    truncIndex--;
}

nanosString = new String(nanosChar, 0, truncIndex + 1);

Have a look at source code of java.sql.Timestamp.toString() method

Upvotes: 1

Related Questions