Dart/Flutter 如何比较两个TimeOfDay时间?

Dart/Flutter How to compare two TimeOfDay times?

TimeOfDay 文档没有比较运算符,原始比较不起作用。我现在唯一能想到的解决方案是将 TimeOfDay 转换为 DateTime 并使用 DateTime 的差异方法。

有没有人有更好的解决方案?

我认为这是不可能的。您可以在 DateTime 中使用 .subtract,也可以使用 .difference

将其转换为双精度然后进行比较。

double toDouble(TimeOfDay myTime) => myTime.hour + myTime.minute/60.0

感谢@Lucas idea,你可以通过

计算小时分钟
TimeOfDay yourTime ; 
TimOfDay nowTime = TimeOfDay.now()

double _doubleYourTime = yourTime.hour.toDouble() +
            (yourTime.minute.toDouble() / 60);
double _doubleNowTime = nowTime.hour.toDouble() +
            (nowTime.minute.toDouble() / 60);

double _timeDiff = _doubleYourTime - _doubleNowTime;

double _hr = _timeDiff.truncate();
double _minute = (_timeDiff - _timeDiff.truncate()) * 60;

print('Here your Happy $_hr Hour and also $_minute min');

我通过将两个值转换为分钟计数并比较它们来计算差异:)

TimeOfDay now = TimeOfDay.now();
int nowInMinutes = now.hour * 60 + now.minute;

TimeOfDay testDate = TimeOfDay(hour: 2, minute: 20);
int testDateInMinutes = testDate.hour * 60 + testDate.minute;
Card(
    child: ListTile(
      onTap: () {
        showTimePicker(
          context: context,
          initialTime: TimeOfDay.now(),
        ).then((TimeOfDay time) {
          double _doubleyourTime =
              time.hour.toDouble() + (time.minute.toDouble() /60);
          double _doubleNowTime = TimeOfDay.now().hour.toDouble() +
              (TimeOfDay.now().minute.toDouble() / 60);`enter code here`
          if (_doubleyourTime > _doubleNowTime) {
           print('correct format')
            });
          } else {
           print('Sorry You can not set the time')
         
          }
        });
      },
      //dense: true,
      leading: Icon(Icons.timer),
      title: Text(
        'Today On Time',`enter code here`
      ),
    ),
  ),
extension TimeOfDayExtension on TimeOfDay {
  int compareTo(TimeOfDay other) {
    if (hour < other.hour) return -1;
    if (hour > other.hour) return 1;
    if (minute < other.minute) return -1;
    if (minute > other.minute) return 1;
    return 0;
  }
}
TimeOfDay n = TimeOfDay.now();
int nowSec = (n.hour * 60 + n.minute) * 60;
int veiSec = (t.hour * 60 + t.minute) * 60;
int dif = veiSec - nowSec;

你可以用这个方法。您必须以 TimesofDay 格式提供开始时间和结束时间的位置。

getTime(startTime, endTime) {
  bool result = false;
  int startTimeInt = (startTime.hour * 60 + startTime.minute) * 60;
  int EndTimeInt = (endTime.hour * 60 + endTime.minute) * 60;
  int dif = EndTimeInt - startTimeInt;

  if (EndTimeInt > startTimeInt) {
    result = true;
  } else {
    result = false;
  }
  return result;
}

点赞

getTime(v1, v2);