How to Comparing only dates of DateTimes in Dart or Flutter Programming| Dart by Example

In Dart, the DateTime object stores Date and Time data.

Suppose if you want to compare the dates of two DateTime objects, The month, day, and year of two dates are equal.

How to Compare only dates of DateTimes in Dart?

Create three Date time objects,

  • First object date1 is using now() - 2022-04-10 20:48:56.354
  • Second object date2 created by adding duration of 10 seconds - 2022-04-10 20:49:06.354
  • Third object date3 created by adding duration of 10 days - 2022-04-20 20:48:56.354
  • date1 and date2 are equal, and date1,and date3 or date2 and date3 are not equal

There are multiple ways we can check only the Dates of a DateTime object.

  • Compare year, month, and day using extension

In this example, Created an extension method that returns true if two objects are equal.

Here is an example program

void main() {
  DateTime date1 = DateTime.now();
  print(date1); //2022-04-10 20:48:56.354


  var date2 = date1.add(Duration(seconds: 10));
  print(date2); //2022-04-10 20:49:06.354

  var date3 = date1.add(Duration(days: 10));
  print(date3); //2022-04-20 20:48:56.354


  print(date1.isDateEqual(date2)); // true
  print(date1.isDateEqual(date3)); // false

  print(date1.isDateEqual(date3)); // false
}

extension CompareDates on DateTime {
  bool isDateEqual(DateTime date2) {
    return year == date2.year && month == date2.month && day == date2.day;
  }
}


Output:

2022-04-10 20:48:56.354
2022-04-10 20:49:06.354
2022-04-20 20:48:56.354
true
false
false
  • use the difference and inDays method:

This example finds the difference between two date objects

Duration difference(DateTime other)

It returns the Duration object, calls inDays that returns a number of days, checks days are zero or not.

Here is an example program.

void main() {
  DateTime date1 = DateTime.now();
  print(date1); //2022-04-10 20:48:56.354

  var date2 = date1.add(Duration(seconds: 10));
  print(date2); //2022-04-10 20:49:06.354

  var date3 = date1.add(Duration(days: 10));
  print(date3); //2022-04-20 20:48:56.354

  print(date1.difference(date2).inDays == 0); // true
  print(date1.difference(date3).inDays == 0); // false

  print(date2.difference(date3).inDays == 0); // false
}

Output:

2022-04-10 20:48:56.354
2022-04-10 20:49:06.354
2022-04-20 20:48:56.354
true
false
false

Conclusion

In this tutorial, several ways to find and compare whether two dates are equal or not by ignoring time fields.