How to Get Difference Between Two DateTime in Dart/Flutter
How to Get Difference Between Two DateTime in Dart/Flutter
In Dart/Flutter, there are several ways to get the difference between two DateTime
objects. Here are some examples:
- Using the difference() method:
The difference() method returns a Duration
object that represents the difference between two DateTime
objects.
DateTime date1 = DateTime(2023, 3, 1, 12, 0, 0); DateTime date2 = DateTime(2023, 3, 18, 12, 0, 0); Duration difference = date2.difference(date1); print(difference); // Output: 17 days, 0:00:00.000000
- Using the inDays property:
The inDays property returns the number of days between two DateTime
objects.
DateTime date1 = DateTime(2023, 3, 1, 12, 0, 0); DateTime date2 = DateTime(2023, 3, 18, 12, 0, 0); int differenceInDays = date2.difference(date1).inDays; print(differenceInDays); // Output: 17
- Using the difference() method and custom functions to extract the difference in specific units:
DateTime date1 = DateTime(2023, 3, 1, 12, 0, 0); DateTime date2 = DateTime(2023, 3, 18, 12, 0, 0); Duration difference = date2.difference(date1); int differenceInDays = difference.inDays; int differenceInHours = difference.inHours % 24; int differenceInMinutes = difference.inMinutes % 60; int differenceInSeconds = difference.inSeconds % 60; print("$differenceInDays days, $differenceInHours hours, $differenceInMinutes minutes, $differenceInSeconds seconds"); // Output: 17 days, 0 hours, 0 minutes, 0 seconds
- Using the
Duration
constructor to create aDuration
object directly:
DateTime date1 = DateTime(2023, 3, 1, 12, 0, 0); DateTime date2 = DateTime(2023, 3, 18, 12, 0, 0); Duration difference = Duration(milliseconds: date2.millisecondsSinceEpoch - date1.millisecondsSinceEpoch); int differenceInDays = difference.inDays; print(differenceInDays); // Output: 17
These are some ways to get the difference between two DateTime
objects in Dart/Flutter. Choose the one that best suits your needs.