Skip to content

Commit 23fefa1

Browse files
authored
Fix the error when calling Timestamp.of(Date date) when date is pre epoch (#3434)
* Fix the error when calling Timestamp.of(Date date) when date is pre epoch.
1 parent 0325488 commit 23fefa1

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

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

+6-3
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,12 @@ public static Timestamp ofTimeSecondsAndNanos(long seconds, int nanos) {
7878
* @throws IllegalArgumentException if the timestamp is outside the representable range
7979
*/
8080
public static Timestamp ofTimeMicroseconds(long microseconds) {
81-
long seconds = TimeUnit.MICROSECONDS.toSeconds(microseconds);
82-
int nanos =
83-
(int) TimeUnit.MICROSECONDS.toNanos(microseconds - TimeUnit.SECONDS.toMicros(seconds));
81+
long seconds = microseconds / 1_000_000;
82+
int nanos = (int)(microseconds % 1_000_000 * 1000);
83+
if (nanos < 0) {
84+
seconds--;
85+
nanos += 1_000_000_000;
86+
}
8487
checkArgument(
8588
Timestamps.isValid(seconds, nanos), "timestamp out of range: %s, %s", seconds, nanos);
8689
return new Timestamp(seconds, nanos);

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

+15
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,9 @@ public class TimestampTest {
3939
private static final long TEST_TIME_MICROSECONDS = 10000100L;
4040
private static final long TEST_TIME_MILLISECONDS =
4141
TimeUnit.SECONDS.toMillis(1444662894L) + TimeUnit.MICROSECONDS.toMillis(1234);
42+
private static final long TEST_TIME_MILLISECONDS_NEGATIVE = -1000L;
4243
private static final Date TEST_DATE = new Date(TEST_TIME_MILLISECONDS);
44+
private static final Date TEST_DATE_PRE_EPOCH = new Date(TEST_TIME_MILLISECONDS_NEGATIVE);
4345

4446
@Rule public ExpectedException expectedException = ExpectedException.none();
4547

@@ -80,6 +82,19 @@ public void ofDate() {
8082
assertThat(timestamp.getNanos()).isEqualTo(expectedNanos);
8183
}
8284

85+
@Test
86+
public void ofDatePreEpoch() {
87+
Timestamp timestamp = Timestamp.of(TEST_DATE_PRE_EPOCH);
88+
long expectedSeconds = TEST_TIME_MILLISECONDS_NEGATIVE / 1_000;
89+
int expectedNanos = (int)(TEST_TIME_MILLISECONDS_NEGATIVE % 1_000 * 1000_000);
90+
if (expectedNanos < 0) {
91+
expectedSeconds--;
92+
expectedNanos += 1_000_000_000;
93+
}
94+
assertThat(timestamp.getSeconds()).isEqualTo(expectedSeconds);
95+
assertThat(timestamp.getNanos()).isEqualTo(expectedNanos);
96+
}
97+
8398
@Test
8499
public void toDate() {
85100
Timestamp timestamp = Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 1234 * 1000);

0 commit comments

Comments
 (0)