ObjectId.fromTimestamp constructor

ObjectId.fromTimestamp(
  1. DateTime timestamp
)

Creates ObjectId from provided timestamp.

Only timestamp segment is set while the rest of the ObjectId is zeroed out.

Example:

final id = ObjectId.fromTimestamp(DateTime.now());

ObjectId structure:

  4 byte timestamp    5 byte process unique   3 byte counter
|<----------------->|<---------------------->|<------------>|
|----|----|----|----|----|----|----|----|----|----|----|----|
0                   4                   8                   12

Implementation

ObjectId.fromTimestamp(DateTime timestamp) {
  ArgumentError.checkNotNull(timestamp, 'timestamp');

  final secondsSinceEpoch = timestamp.millisecondsSinceEpoch ~/ 1000;

  // 4-byte timestamp
  _bytes[3] = secondsSinceEpoch & 0xff;
  _bytes[2] = (secondsSinceEpoch >> 8) & 0xff;
  _bytes[1] = (secondsSinceEpoch >> 16) & 0xff;
  _bytes[0] = (secondsSinceEpoch >> 24) & 0xff;
}