Flutter: Sprawdź, czy data jest między dwiema datami

Oct 17 2020

Muszę sprawdzić, czy data jest między dwiema datami, czy nie.

Próbowałem go wyszukać, ale nie uzyskałem owocnych wyników. Być może widzieliście takie scenariusze. Więc szukam rady.

Oto mój kod.

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

Więc w zasadzie mam datę rozpoczęcia i datę zakończenia. Muszę sprawdzić, czy aktualna data przypada między tymi dwoma datami, czy nie.

Odpowiedzi

5 KuKu Oct 17 2020 at 14:13

Możesz sprawdzić przed / po użyciu „isBefore” i „isAfter” w klasie „DateTime”.

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