Consider the following test code (Try it here yourself on ideone.com - an online Java compiler):
class Main {
public static void main (String[] args) throws Exception {
Main m = new Main();
m.test1();
System.out.println();
m.test2();
}
void test1() throws Exception {
System.out.println("TEST 1: ");
String strTimestamp = "1957-04-27 00:00:00.01";
System.out.println(strTimestamp + " [Original String]");
String format = "yyyy-MM-dd HH:mm:ss.SS";
System.out.println(format + " [Format used]");
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format);
// Convert String to Date:
java.util.Date date = formatter.parse(strTimestamp);
long time = date.getTime();
System.out.println(formatter.format(time) + " [Date#getTime() with same format]");
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
System.out.println(timestamp + " [Timestamp]");
}
void test2() throws Exception {
System.out.println("TEST 2: ");
String strTimestamp = "1957-04-27 00:00:00.001";
System.out.println(strTimestamp + " [Original String]");
String format = "yyyy-MM-dd HH:mm:ss.SSS";
System.out.println(format + " [Format used]");
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format);
// Convert String to Date:
java.util.Date date = formatter.parse(strTimestamp);
long time = date.getTime();
System.out.println(formatter.format(time) + " [Date#getTime() with same format]");
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
System.out.println(timestamp + " [Timestamp]");
}
}
The code above gives the following output:
TEST 1:
1957-04-27 00:00:00.01 [Original String]
yyyy-MM-dd HH:mm:ss.SS [Format used]
1957-04-27 00:00:00.01 [Date#getTime() with same format]
1957-04-27 00:00:00.001 [Timestamp]
TEST 2:
1957-04-27 00:00:00.001 [Original String]
yyyy-MM-dd HH:mm:ss.SSS [Format used]
1957-04-27 00:00:00.001 [Date#getTime() with same format]
1957-04-27 00:00:00.001 [Timestamp]
In TEST 1
I was expecting the [Original String]
, [Date#getTime() with same format]
AND [Timestamp]
to all have the same output just like at TEST 2
.
Why does the [Timestamp]
in TEST 1
have an extra zero compared to the Date?