exactDiff function

num exactDiff (
  1. {@required DateTime x,
  2. @required DateTime y,
  3. String units: "ms",
  4. bool asFloat: false}
)

Returns exact amount of given unit (units) between the two DateTimes. This accounts for leapyears and other time-based anomalies.

Accepted units are:

  • 'ms' (milliseconds)

  • 's' (seconds)

  • 'min' (minutes)

  • 'h' (hours)

  • 'd' (days)

  • 'w' (weeks)

  • 'mon' (months)

  • 'y' (years)

Implementation

num exactDiff(
    {@required DateTime x,
    @required DateTime y,
    String units = "ms",
    bool asFloat = false}) {
  num diff;
  switch (units) {
    case "ms":
      diff = x.difference(y).inMilliseconds;
      break;
    case "s":
      diff = x.difference(y).inSeconds;
      break;
    case "min":
      diff = x.difference(y).inMinutes;
      break;
    case "h":
      diff = x.difference(y).inHours;
      break;
    case "d":
      diff = x.difference(y).inDays;
      break;
    case "w":
      diff = x.difference(y).inDays / 7;
      break;
    case "mon":
      diff = _monthDiff(x, y);
      break;
    case "y":
      diff = _monthDiff(x, y) / 12;
      break;
    default:
      throw ArgumentError("Unsupported format...");
  }
  if (!asFloat) return _absFloor(diff);
  return diff;
}