Skip to content

[cloud_firestore] Timestamp class miscalculates microseconds and milliseconds #1222

@kroikie

Description

@kroikie

To test the Timestamp class in "Timestamp.dart" file, try this:

int _kEndOfTime = 253402300800;
var maxTimestamp = Timestamp(_kEndOfTime - 1, _kBillion - 1);
Timestamp.fromMicrosecondsSinceEpoch(maxTimestamp.microsecondsSinceEpoch)

You get this error:

Invalid argument(s): Timestamp seconds out of range: 253402300800

The problem is the use of double (floating point) in calculations, which obviously results in rounding mistakes. Please note, this won't throw errors when the date is far from the Timestamp range limits, but will still miscalculate the number of microseconds! So this must be fixed as soon as possible.

I believe the code should be changed into this:

factory Timestamp.fromMillisecondsSinceEpoch(int milliseconds) {
  final int seconds = (milliseconds ~/ _kThousand);
  final int nanoseconds = (milliseconds - seconds * _kThousand) * _kMillion;
  return Timestamp(seconds, nanoseconds);
}

factory Timestamp.fromMicrosecondsSinceEpoch(int microseconds) {
  final int seconds = (microseconds ~/ _kMillion);
  final int nanoseconds = (microseconds - seconds * _kMillion) * _kThousand;
  return Timestamp(seconds, nanoseconds);
}

int get millisecondsSinceEpoch => (seconds * _kThousand + nanoseconds ~/ _kMillion);

int get microsecondsSinceEpoch => (seconds * _kMillion + nanoseconds ~/ _kThousand);

Metadata

Metadata

Assignees

Labels

impact: crowdAffects many people, though not necessarily a specific customer with an assigned label. (P2)plugin: cloud_firestoretype: bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions