Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handy little util for calculating time intervals between two DateTime in Dart.
void main() {
calculateDateInterval(DateTime(2020, 09, 22, 11, 00), DateTime(2020, 09, 22, 16, 00), 0.75);
}
void calculateDateInterval(
final DateTime startTime,
final DateTime endTime,
final double intervalInHours,
) {
final workingHours = endTime.difference(startTime).inHours;
const milliSecondsInHour = 3600000;
final interval = (intervalInHours * milliSecondsInHour).round();
final workingDayInMilliseconds = workingHours * milliSecondsInHour;
final avaibleTimeSlots = (workingDayInMilliseconds ~/ interval);
final slots = <String>[];
for (var offset = 1; offset < avaibleTimeSlots; offset++) {
final timeOffset = startTime.millisecondsSinceEpoch + (offset * interval);
slots.add(DateTime.fromMillisecondsSinceEpoch(timeOffset).toString());
}
print(slots);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment