Skip to content

Commit

Permalink
Fix rounding when handling negative timestamps (#580)
Browse files Browse the repository at this point in the history
  • Loading branch information
sigurdm authored Mar 19, 2022
1 parent 8afce8d commit 2546269
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion protobuf/lib/src/protobuf/mixins/well_known.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
11 changes: 11 additions & 0 deletions protoc_plugin/test/timestamp_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 2546269

Please sign in to comment.