I have a showTimePicker in my app and I want to compare between the picked time and the current real time.
I tried to used DateTime.now() and compare it to the value that was picked but the value is TimeOfDay and also DateTime.now() has year,month, day.. etc.
The scenario I want is that when a user picks a time after choosing a date I want my app to check if this time is overdue or not.
CodePudding user response:
You can convert the picked TimeOfDay
value to a DateTime object using the following code:
DateTime pickedDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, pickedTime.hour, pickedTime.minute);
Then you can compare the current DateTime.now()
value with the pickedDate value.
if (pickedDate.isAfter(DateTime.now())) {
// time is in future
} else if (pickedDate.isBefore(DateTime.now())) {
// time is overdue
}
CodePudding user response:
I have write a extension for TimeOfDay, I think you can use func on this extension.
import 'package:flutter/material.dart';
extension TimeOfDayExtension on TimeOfDay {
bool isBefore(TimeOfDay other) {
return (60 * hour minute) < (60 * other.hour other.minute);
}
bool theSame(TimeOfDay other) {
return (60 * hour minute) == (60 * other.hour other.minute);
}
bool isBeforeNow() {
return isBefore(TimeOfDay.fromDateTime(DateTime.now()));
}
bool theSameNow() {
return theSame(TimeOfDay.fromDateTime(DateTime.now()));
}
bool isBeforeDate(DateTime date) {
return isBefore(TimeOfDay.fromDateTime(date));
}
bool theSameDate(DateTime date) {
return theSame(TimeOfDay.fromDateTime(date));
}
}
CodePudding user response:
In order to compare two TimeOfDay
objects in Flutter, you can use the compareTo
method provided by the TimeOfDay
class. This method compares the time of one TimeOfDay
object to another and returns a negative integer if the first time is earlier than the second, a positive integer if the first time is later than the second, and 0 if the times are equal.
Here is an example of how you can use the compareTo method to compare two TimeOfDay
objects:
TimeOfDay time1 = TimeOfDay.now();
TimeOfDay time2 = TimeOfDay(hour: 14, minute: 30);
int comparison = time1.format(context).compareTo(time2.format(context));
if (comparison < 0) {
print("Time 1 is earlier than Time 2");
} else if (comparison > 0) {
print("Time 1 is later than Time 2");
} else {
print("Time 1 is the same as Time 2");
}
Please note that the showTimePicker
method just shows a dialog to pick the time, it doesn't return any value.
You should use the then
method in the Future returned by the showTimePicker
to get the selected time.
TimeOfDay selectedTime;
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
).then((value) {
if (value != null) {
setState(() {
selectedTime = value;
});
}
});
Then you can use the selectedTime variable to compare with another time.