简体   繁体   English

如何使用 IF 条件比较 Flutter (dart) 中的两个 DateTime 值?

[英]How to compare two DateTime values in Flutter (dart) using IF condition?

how to Compare to DateTime value like Nowtime(10.13 pm) and Compare with future timelike (10:15 pm), these two-time compare in if Condition, this is true then perform task else showing Error如何比较像现在时间(10.13 pm)和未来时间(10:15 pm)这样的日期时间值,这两次比较在 if 条件下,这是真的,然后执行任务,否则显示错误

String formattedtime = DateFormat('h:mm a').format(DateTime.now());
//getting Current time is formattedtime
// time is stored in database and comapre with this
if(date==formattedDate &&formattedtime==time &&status =='false'){

}else{
     // else condition
 }

// remove time condition then working fine 

if(date==formattedDate&&status =='false'){

  // this condition working Fine but with Time Compare not working 

}else{
     // else condition
 }

not working不工作

I don't know how to compare these result, I just want to if the current time is greater then or equal to time(that's in a database)then perform the task我不知道如何比较这些结果,我只想如果当前时间大于或等于时间(在数据库中)然后执行任务

thanks谢谢

Convert into DateTime and use isAfter or isBefore to compare转换为DateTime并使用isAfterisBefore进行比较

DateTime date1 = DateTime.now();
System.out.println(date1);
DateTime date2 = DateTime.now().plusDays(1);
System.out.println(date2);
System.out.println(date1.isBefore(date2));     //true
System.out.println(date1.isAfter(date2));      //false
 DateFormat dateFormat = DateFormat.jm();// this is the format like(5:08 PM)
 DateTime now =  DateTime.now();// current time 
 DateTime open = dateFormat.parse(time); // time is dynamic value database
 open = DateTime(now.year, now.month, now.day, open.hour, open.minute);

 // here your condition

 if(now.isAfter(open)){
   // task here
  }else{
 }

只需将 DateTime 转换为 millisecondsSinceEpoch 值,然后比较整数值

What you can do is你能做的是

final startTime = DateTime(2018, 6, 23, 10, 30);
final endTime = DateTime(2018, 6, 23, 13, 00);

final currentTime = DateTime.now();
      
if(currentTime.isAfter(startTime) && currentTime.isBefore(endTime)) {
  // do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM