I’m working on a Flutter project where I need to compare two DateTime objects, but only by their date. The time component of the DateTime objects is not relevant for my comparison.
Here’s an example of the DateTime objects I’m dealing with:
Dart
DateTime dt1 = DateTime.parse("2023-11-10 11:47:00");
DateTime dt2 = DateTime.parse("2023-11-10 10:09:00");
I want to compare dt1 and dt2 such that only the date (year, month, day) is considered, not the time. How can I achieve this in Flutter? Any help would be appreciated. Thanks!
2
Answers
In Flutter, you can compare two
DateTime
objects with respect to only the date (not time) by creating newDateTime
objects from the original ones that contain only the year, month, and day information. Here's an example:In this code,
date1
anddate2
are newDateTime
objects created fromdt1
anddt2
respectively, but they only contain the year, month, and day information. The time is set to 00:00:00 by default. Therefore, when you comparedate1
anddate2
, you're effectively comparing the dates only, not the times.1) Creating new Date objects using only year, month, and day attributes
Or as an extension method:
2) If you don’t want to create new objects
You can compare
year
,month
, andday
attributes of yourDateTime
objects:This is another way to do it: