This repository was archived by the owner on Dec 3, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +37
-1
lines changed
main/java/com/google/cloud
test/java/com/google/cloud Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change @@ -119,7 +119,19 @@ public static Timestamp now() {
119119 * @throws IllegalArgumentException if the timestamp is outside the representable range
120120 */
121121 public static Timestamp of (java .sql .Timestamp timestamp ) {
122- return ofTimeSecondsAndNanos (timestamp .getTime () / 1000 , timestamp .getNanos ());
122+ int nanos = timestamp .getNanos ();
123+
124+ // A pre-epoch timestamp will be off by one second because of the way that integer division
125+ // works. For example, -1001 / 1000 == -1. In this case of timestamps, we want this result to be
126+ // -2. This causes any pre-epoch timestamp to be off by 1 second - fix this by adjusting the
127+ // seconds value by 1 if the timestamp < 0.
128+ // TODO: replace with Math.floorDiv when we drop Java 7 support
129+ long seconds = timestamp .getTime () / 1000 ;
130+ if (seconds < 0 ) {
131+ --seconds ;
132+ }
133+
134+ return Timestamp .ofTimeSecondsAndNanos (seconds , nanos );
123135 }
124136
125137 /**
Original file line number Diff line number Diff line change @@ -80,6 +80,30 @@ public void ofDate() {
8080 assertThat (timestamp .getNanos ()).isEqualTo (expectedNanos );
8181 }
8282
83+ @ Test
84+ public void ofSqlTimestamp () {
85+ String expectedTimestampString = "1970-01-01T00:00:12.345000000Z" ;
86+ java .sql .Timestamp input = new java .sql .Timestamp (12345 );
87+ Timestamp timestamp = Timestamp .of (input );
88+ assertThat (timestamp .toString ()).isEqualTo (expectedTimestampString );
89+ }
90+
91+ @ Test
92+ public void ofSqlTimestampPreEpoch () {
93+ String expectedTimestampString = "1969-12-31T23:59:47.655000000Z" ;
94+ java .sql .Timestamp input = new java .sql .Timestamp (-12345 );
95+ Timestamp timestamp = Timestamp .of (input );
96+ assertThat (timestamp .toString ()).isEqualTo (expectedTimestampString );
97+ }
98+
99+ @ Test
100+ public void ofSqlTimestampOnEpoch () {
101+ String expectedTimestampString = "1970-01-01T00:00:00Z" ;
102+ java .sql .Timestamp input = new java .sql .Timestamp (0 );
103+ Timestamp timestamp = Timestamp .of (input );
104+ assertThat (timestamp .toString ()).isEqualTo (expectedTimestampString );
105+ }
106+
83107 @ Test
84108 public void ofDatePreEpoch () {
85109 Timestamp timestamp = Timestamp .of (TEST_DATE_PRE_EPOCH );
You can’t perform that action at this time.
0 commit comments