From 2546269c5f5585a074457b4f9a9a80bf5f3fb268 Mon Sep 17 00:00:00 2001 From: Sigurd Meldgaard Date: Sat, 19 Mar 2022 10:43:53 +0100 Subject: [PATCH] Fix rounding when handling negative timestamps (#580) --- protobuf/lib/src/protobuf/mixins/well_known.dart | 2 +- protoc_plugin/test/timestamp_test.dart | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/protobuf/lib/src/protobuf/mixins/well_known.dart b/protobuf/lib/src/protobuf/mixins/well_known.dart index e5215b231..e7ac9fea4 100644 --- a/protobuf/lib/src/protobuf/mixins/well_known.dart +++ b/protobuf/lib/src/protobuf/mixins/well_known.dart @@ -160,7 +160,7 @@ abstract class TimestampMixin { /// Time zone information will not be preserved. static void setFromDateTime(TimestampMixin target, DateTime dateTime) { var micros = dateTime.microsecondsSinceEpoch; - target.seconds = Int64(micros ~/ Duration.microsecondsPerSecond); + target.seconds = Int64((micros / Duration.microsecondsPerSecond).floor()); target.nanos = (micros % Duration.microsecondsPerSecond).toInt() * 1000; } diff --git a/protoc_plugin/test/timestamp_test.dart b/protoc_plugin/test/timestamp_test.dart index 5d02e21af..6203139ff 100644 --- a/protoc_plugin/test/timestamp_test.dart +++ b/protoc_plugin/test/timestamp_test.dart @@ -23,6 +23,17 @@ void main() { expect(fromProto, dateTime); }); + test('negative Timestamp', () { + final secondBeforeEpoch = Timestamp(seconds: Int64(-1), nanos: 1000000); + var dateTime = DateTime.fromMillisecondsSinceEpoch(-999, isUtc: true); + + expect(secondBeforeEpoch.toDateTime().millisecondsSinceEpoch, + dateTime.millisecondsSinceEpoch); + expect(secondBeforeEpoch.toDateTime(), dateTime); + expect(Timestamp.fromDateTime(dateTime).nanos, 1000000); + expect(Timestamp.fromDateTime(dateTime).seconds, Int64(-1)); + }); + test('local datetime -> timestamp -> datetime', () { var dateTime = DateTime(2019, 02, 15, 10, 21, 25, 5, 5); var fromProto = Timestamp.fromDateTime(dateTime).toDateTime();