Flutter: Check if date is between two dates

Viewed 9289

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.

3 Answers

You can check before/after using 'isBefore' and 'isAfter' in 'DateTime' class.
enter image description here

    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));

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().isAfter(yourDate)

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

Don't forget to check if the day is the same as the one of the two dates also by adding an or to the condition ex: if ( start is before now || (start.month==now.month && start.day==now.day ...etc)

Related