diff function
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
}