From 5999a02891a1936c732b0fb13e2bd0cfb2c446e8 Mon Sep 17 00:00:00 2001 From: NathanGrand Date: Wed, 27 Jul 2022 16:01:55 +0100 Subject: [PATCH] Fix Timestamps fromDate for negative 'exact second' java.sql.Timestamps --- .../src/main/java/com/google/protobuf/util/Timestamps.java | 2 +- .../test/java/com/google/protobuf/util/TimestampsTest.java | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java b/java/util/src/main/java/com/google/protobuf/util/Timestamps.java index ea8a9334bc..0b09fccd2a 100644 --- a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java +++ b/java/util/src/main/java/com/google/protobuf/util/Timestamps.java @@ -344,7 +344,7 @@ public final class Timestamps { if (date instanceof java.sql.Timestamp) { java.sql.Timestamp sqlTimestamp = (java.sql.Timestamp) date; long time = sqlTimestamp.getTime(); - long integralSeconds = (time < 0) ? time / 1000L - 1 : time / 1000L ; // truncate the fractional seconds + long integralSeconds = (time < 0 && time % 1000 != 0) ? time / 1000L - 1 : time / 1000L ; // truncate the fractional seconds return Timestamp.newBuilder() .setSeconds(integralSeconds) .setNanos(sqlTimestamp.getNanos()) diff --git a/java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java b/java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java index 7d0d821c3f..51f7a85b49 100644 --- a/java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java +++ b/java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java @@ -483,6 +483,13 @@ public class TimestampsTest { assertThat(Timestamps.toString(timestamp)).isEqualTo("1969-12-31T23:59:58.889Z"); } + @Test + public void testFromSqlTimestamp_beforeEpochWholeSecond() { + Date date = new java.sql.Timestamp(-2000); + Timestamp timestamp = Timestamps.fromDate(date); + assertThat(Timestamps.toString(timestamp)).isEqualTo("1969-12-31T23:59:58Z"); + } + @Test public void testTimeOperations() throws Exception { Timestamp start = Timestamps.parse("0001-01-01T00:00:00Z");