I have 3 dates like
Date1 = 2022-02-07 20:06:14.379392
Date2 = 2021-02-07 20:06:14.379393
Date3 = 2022-02-06 00:00:00.000
I want to check if Date3 comes between Date1 and Date2. As of right now Date3 comes between Date1 and 2. How can I check this?
I am trying something like this
if (Date1.isBefore(
Date3) &&
Date2.isAfter(
Date3)) {
print(
"date3 is between date1 and date2");
} else {
print(
"date3 isn't between date1 and date2");
}
But it's always showing that the date3 is not between 1 and 2.
CodePudding user response:
You have interchanged the dates in the if-condition.
Instead of checking, if 2022-02-06 is before 2022-02-07, you are currently checking 2022-02-07 is before 2022-02-06. Which is obviously wrong.
So you have to adjust your check.
For Example:
void main() {
var now = DateTime.now();
var lastYear = DateTime.now().add(Duration(days: -365));
var dateToCheck = DateTime.now().add(Duration(days: -1));
if( dateToCheck.isAfter(lastYear) && dateToCheck.isBefore(now))
{
print("dateToCheck is between now and lastYear");
}
else
{
print("dateToCheck is not between now and lastYear");
}
}
or if you want to write dateToCheck
within the function call, you could write it like this:
void main() {
var now = DateTime.now();
var lastYear = DateTime.now().add(Duration(days: -365));
var dateToCheck = DateTime.now().add(Duration(days: -1));
if( lastYear.isBefore(dateToCheck) && now.isAfter(dateToCheck) )
{
print("dateToCheck is between now and lastYear");
}
else
{
print("dateToCheck is not between now and lastYear");
}
}
CodePudding user response:
If you parse the dates as DateTime then fix the condition, it should work. Side note: you should rename your variables to something more explicit, ex. dateMin/dateMax, dateLowerBound/dateUpperBound, etc.
void main() {
final date1 = DateTime.parse('2022-02-07 20:06:14.379392');
final date2 = DateTime.parse('2021-02-07 20:06:14.379393');
final date3 = DateTime.parse('2022-02-06 00:00:00.000');
if (date3.isBefore(date1) && date3.isAfter(date2)) {
print("date3 is between date1 and date2"); // <- this is printed.
}
else {
print("date3 isn't between date1 and date2");
}
}