简体   繁体   English

Flutter:检查日期是否在两个日期之间

[英]Flutter: Check if date is between two dates

I need to check date is between two dates or not.我需要检查日期是否在两个日期之间。

I tried to search it but didn't got fruitful results.我试图搜索它,但没有得到丰硕的结果。 May be you have seen such scenarios.可能你见过这样的场景。 So, seeking your advise.所以,寻求你的建议。

Here is my code.这是我的代码。

var service_start_date = '2020-10-17';
var service_end_date = '2020-10-23';
var service_start_time = '10:00:00';
var service_end_time = '11:00:00';

DateTime currentDate = new DateTime.now();
DateTime times = DateTime.now();


  @override
  void initState() {
    super.initState();
    test();
  }

 test() {
    String currenttime = DateFormat('HH:mm').format(times);
    String currentdate = DateFormat('yyyy-mm-dd').format(currentDate);
    print(currenttime);    
    print(currentdate);
    
  }

So, basically i have start date and end date.所以,基本上我有开始日期和结束日期。 I need to check current date is falling between these two dates or not.我需要检查当前日期是否介于这两个日期之间。

You can check before/after using 'isBefore' and 'isAfter' in 'DateTime' class.您可以在“DateTime”类中使用“isBefore”和“isAfter”之前/之后检查。
在此处输入图片说明

    DateTime startDate = DateTime.parse(service_start_date);
  DateTime endDate = DateTime.parse(service_end_date);
  
  DateTime now = DateTime.now();
  
  print('now: $now');
  print('startDate: $startDate');
  print('endDate: $endDate');
  print(startDate.isBefore(now));
  print(endDate.isAfter(now));

不要忘记检查这一天是否与两个日期之一相同,也可以通过在条件中添加一个 or 来检查: if ( start is before now || (start.month==now.month && start.day ==now.day ...等)

I've made a series of extensions我做了一系列的扩展

extension DateTimeExtension on DateTime? {
  
  bool? isAfterOrEqualTo(DateTime dateTime) {
    final date = this;
    if (date != null) {
      final isAtSameMomentAs = dateTime.isAtSameMomentAs(date);
      return isAtSameMomentAs | date.isAfter(dateTime);
    }
    return null;
  }

  bool? isBeforeOrEqualTo(DateTime dateTime) {
    final date = this;
    if (date != null) {
      final isAtSameMomentAs = dateTime.isAtSameMomentAs(date);
      return isAtSameMomentAs | date.isBefore(dateTime);
    }
    return null;
  }

  bool? isBetween(
    DateTime fromDateTime,
    DateTime toDateTime,
  ) {
    final date = this;
    if (date != null) {
      final isAfter = date.isAfterOrEqualTo(fromDateTime) ?? false;
      final isBefore = date.isBeforeOrEqualTo(toDateTime) ?? false;
      return isAfter && isBefore;
    }
    return null;
  }

}

I'm hoping they're self explanatory but obviously you can call them like我希望它们是不言自明的,但显然你可以这样称呼它们

DateTime.now().isBefore(yourDate) DateTime.now().isBefore(yourDate)

DateTime.now().isAfter(yourDate) DateTime.now().isAfter(yourDate)

DateTime.now().isBetween(fromDate, toDate) DateTime.now().isBetween(fromDate, toDate)

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

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