From bfa663ab687813d2a0fb39724a0130ed4896519e Mon Sep 17 00:00:00 2001 From: NathanGrand Date: Thu, 9 Jun 2022 21:04:49 +0100 Subject: [PATCH] Fix Timestamps.fromDate to correctly handle java.sql.Timestamps before unix epoch. --- .../src/main/java/com/google/protobuf/util/Timestamps.java | 3 ++- .../test/java/com/google/protobuf/util/TimestampsTest.java | 7 +++++++ 2 files changed, 9 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 95f3665fab..ea8a9334bc 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 @@ -343,7 +343,8 @@ public final class Timestamps { public static Timestamp fromDate(Date date) { if (date instanceof java.sql.Timestamp) { java.sql.Timestamp sqlTimestamp = (java.sql.Timestamp) date; - long integralSeconds = sqlTimestamp.getTime() / 1000L; // truncate the fractional seconds + long time = sqlTimestamp.getTime(); + long integralSeconds = (time < 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 ea90a6b208..7d0d821c3f 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 @@ -475,6 +475,13 @@ public class TimestampsTest { Timestamp timestamp = Timestamps.fromDate(date); assertThat(Timestamps.toString(timestamp)).isEqualTo("1970-01-01T00:00:01.111Z"); } + + @Test + public void testFromSqlTimestamp_beforeEpoch() { + Date date = new java.sql.Timestamp(-1111); + Timestamp timestamp = Timestamps.fromDate(date); + assertThat(Timestamps.toString(timestamp)).isEqualTo("1969-12-31T23:59:58.889Z"); + } @Test public void testTimeOperations() throws Exception {