Async and Practical
DateTime Difference and Duration
Calling end.difference(start) compares two DateTime values and returns a Duration. From there, inMinutes gives the total minutes, and integer division and modulo split that into hours and leftover minutes.
Program
Play the program to compute the elapsed time between 09:05 and 10:45 UTC.
duration_difference.dart
void main() {
var start = DateTime.utc(2024, 7, 4, 9, 5);
var end = DateTime.utc(2024, 7, 4, 10, 45);
var elapsed = end.difference(start);
var totalMinutes = elapsed.inMinutes;
var hours = totalMinutes ~/ 60;
var minutes = totalMinutes % 60;
print('elapsed=${hours}h ${minutes}m');
}
difference
`end.difference(start)` returns a `Duration` between two `DateTime` values; here, 100 minutes.
inMinutes
`Duration.inMinutes` exposes the total whole minutes, ignoring sub-minute resolution.
split with ~/ and %
`totalMinutes ~/ 60` is the hour count and `totalMinutes % 60` is the leftover minutes.