check if datetime variable is today, tomorrow or yesterday
While the above answer is correct, I would like to provide a more compact and flexible alternative :
/// Returns the difference (in full days) between the provided date and today.
int calculateDifference(DateTime date) {
DateTime now = DateTime.now();
return DateTime(date.year, date.month, date.day).difference(DateTime(now.year, now.month, now.day)).inDays;
}
So if you want to check if date
is :
- Yesterday :
calculateDifference(date) == -1
. - Today :
calculateDifference(date) == 0
. - Tomorrow :
calculateDifference(date) == 1
.
@34mo 's answer updated for flutter lint 2021
extension DateUtils on DateTime {
bool get isToday {
final now = DateTime.now();
return now.day == day && now.month == month && now.year == year;
}
bool get isTomorrow {
final tomorrow = DateTime.now().add(const Duration(days: 1));
return tomorrow.day == day &&
tomorrow.month == month &&
tomorrow.year == year;
}
bool get isYesterday {
final yesterday = DateTime.now().subtract(const Duration(days: 1));
return yesterday.day == day &&
yesterday.month == month &&
yesterday.year == year;
}
}
Using dart extensions can help make your code more elegant. You can create a utility class with the following:
extension DateHelpers on DateTime {
bool isToday() {
final now = DateTime.now();
return now.day == this.day &&
now.month == this.month &&
now.year == this.year;
}
bool isYesterday() {
final yesterday = DateTime.now().subtract(Duration(days: 1));
return yesterday.day == this.day &&
yesterday.month == this.month &&
yesterday.year == this.year;
}
}
And then whenever you need to know if a day is today or yesterday, import the utility class into the file where you need it and then call the appropriate function like it was inbuilt in the DateTime
class.
Text(
myDate.isToday() ? "Today"
: myDate.isYesterday() ? "Yesterday"
: DateFormat("dd MMM").format(myDate)
)
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final yesterday = DateTime(now.year, now.month, now.day - 1);
final tomorrow = DateTime(now.year, now.month, now.day + 1);
final dateToCheck = ...
final aDate = DateTime(dateToCheck.year, dateToCheck.month, dateToCheck.day);
if(aDate == today) {
...
} else if(aDate == yesterday) {
...
} else(aDate == tomorrow) {
...
}
Hit: now.day - 1
and now.day + 1
works well with dates that result in a different year or month.