Skip to content
This repository was archived by the owner on Dec 3, 2023. It is now read-only.

Commit 0030226

Browse files
committed
fix: fix conversion for timestamps pre-epoch
1 parent 2ce2f8d commit 0030226

2 files changed

Lines changed: 25 additions & 4 deletions

File tree

google-cloud-core/src/main/java/com/google/cloud/Timestamp.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,13 @@ 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+
// TODO: replace with Math.floorDiv when we drop Java 7 support
123+
long secs = timestamp.getTime() / 1000;
124+
int nanos = timestamp.getNanos();
125+
if (secs < 0) {
126+
--secs;
127+
}
128+
return Timestamp.ofTimeSecondsAndNanos(secs, nanos);
123129
}
124130

125131
/**

google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,24 @@ public void ofDate() {
8282

8383
@Test
8484
public void ofSqlTimestamp() {
85-
String timestampString = "1950-01-01 01:23:45.123456789";
86-
String expectedTimestamp = "1950-01-01T09:23:45.123456789Z";
87-
java.sql.Timestamp input = java.sql.Timestamp.valueOf(timestampString);
85+
String expectedTimestamp = "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(expectedTimestamp);
89+
}
90+
91+
@Test
92+
public void ofSqlTimestampPreEpoch() {
93+
String expectedTimestamp = "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(expectedTimestamp);
97+
}
98+
99+
@Test
100+
public void ofSqlTimestampOnEpoch() {
101+
String expectedTimestamp = "1970-01-01T00:00:00Z";
102+
java.sql.Timestamp input = new java.sql.Timestamp(0);
88103
Timestamp timestamp = Timestamp.of(input);
89104
assertThat(timestamp.toString()).isEqualTo(expectedTimestamp);
90105
}

0 commit comments

Comments
 (0)