diff function

int diff(
  1. DateTime start,
  2. DateTime end, [
  3. String unit = 'day'
])

Implementation

int diff(DateTime start, DateTime end, [String unit = 'day']) {
  if (unit == 'year') {
    return end.year - start.year;
  } else if (unit == 'month') {
    return (end.year - start.year) * 12 + end.month - start.month;
  } else if (unit == 'week') {
    return (end.millisecondsSinceEpoch - start.millisecondsSinceEpoch) ~/
        (1000 * 60 * 60 * 24 * 7);
  } else if (unit == 'day') {
    return (end.millisecondsSinceEpoch - start.millisecondsSinceEpoch) ~/
        (1000 * 60 * 60 * 24);
  } else if (unit == 'hour') {
    return (end.millisecondsSinceEpoch - start.millisecondsSinceEpoch) ~/
        (1000 * 60 * 60);
  } else if (unit == 'minute') {
    return (end.millisecondsSinceEpoch - start.millisecondsSinceEpoch) ~/
        (1000 * 60);
  } else if (unit == 'second') {
    return (end.millisecondsSinceEpoch - start.millisecondsSinceEpoch) ~/ 1000;
  } else if (unit == 'millisecond') {
    return end.millisecondsSinceEpoch - start.millisecondsSinceEpoch;
  } else {
    throw Exception('Invalid unit: $unit');
  }

  // example:
  // diff(DateTime(2020, 2, 28), DateTime(2020, 3, 1), 'week') => 1
}