Timestamp.fromDate constructor

Timestamp.fromDate(
  1. DateTime date
)

Creates a new timestamp from date, with microsecond precision (the precision of DateTime on the Dart VM, and of the Firestore backend).

Throws an ArgumentError if the result is outside the supported range.

When compiled to JavaScript, a DateTime holds only milliseconds, and so does the timestamp.

final Timestamp t = Timestamp.fromDate(DateTime.now());

Implementation

factory Timestamp.fromDate(DateTime date) {
  final int microseconds = date.microsecondsSinceEpoch;
  // Floor division, so that negative values keep non-negative nanoseconds.
  int seconds = microseconds ~/ 1000000;
  int nanoseconds = microseconds.remainder(1000000) * 1000;

  if (nanoseconds < 0) {
    seconds -= 1;
    nanoseconds += 1000000000;
  }

  _validateRange(seconds, nanoseconds);
  return Timestamp(seconds, nanoseconds);
}