fromSafeMillisecondsSinceEpoch static method

DateTime fromSafeMillisecondsSinceEpoch(
  1. int milliseconds, {
  2. DateTime? current,
})

Converts a safe milliseconds-since-epoch value back into a DateTime.

The milliseconds value may exceed the 32-bit signed integer range. It is resolved relative to the appropriate time period (epoch cycle), using current to determine which period the timestamp belongs to.

current defaults to DateTime.now().toUtc() if not provided.

Throws ArgumentError if milliseconds exceeds the safe range defined by maxDateTime.

Implementation

static DateTime fromSafeMillisecondsSinceEpoch(int milliseconds, {DateTime? current}) {
  if (milliseconds > maxDateTime.safeMillisecondsSinceEpoch) {
    throw ArgumentError("The milliseconds value $milliseconds exceeds the maximum safe timestamp.");
  }

  current ??= DateTime.now().toUtc();
  var baseEpoch = DateTime.utc(1970, 1, 1);
  var periodLeft = baseEpoch;
  var periodRight = baseEpoch.add(Duration(milliseconds: 0x7fffffff));
  while ((current > periodLeft && current <= periodRight) == false) {
    periodLeft = periodRight;
    periodRight = periodRight.add(Duration(milliseconds: 0x7fffffff));
  }
  return DateTime.fromMillisecondsSinceEpoch(milliseconds) + periodLeft.difference(baseEpoch);
}