BIS Tech
BIS Tech

Reputation: 19444

How to determine which DateTime is greater or less than the other

How it should work:

Make sure that today is between 2020-April-01(timestampValidFrom - firebase timestamp format) and 2020-April-05(timestampValidTo).

I need like this query.

1)

timestampValidFrom <= today >= timestampValidTo

or

2)

 .where('timestampValidFrom', isGreaterThanOrEqualTo: Timestamp.now())
 .where('timestampValidTo', isLessThanOrEqualTo: Timestamp.now())

I have tried to fix this solution, but it does not work.

DateTime now = DateTime.now();
DateTime yesterday,tomorrow;

yesterday = DateTime(now.year, now.month, now.day); // today 12.00.00
tomorrow = DateTime(now.year, now.month, now.day +1); //tomorrow 12.00.00

if(yesterday.isAfter(snapshot.data[index].timestampValidFrom.toDate())
    || snapshot.data[index].timestampValidFrom.toDate().isBefore(tomorrow) 
    && yesterday.isBefore(snapshot.data[index].timestampValidTo.toDate())
    || snapshot.data[index].timestampValidTo.toDate().isAfter(tomorrow)) {
    // show widget
} else {
    //emplty widget
}

Upvotes: 0

Views: 2123

Answers (3)

jamesdlin
jamesdlin

Reputation: 90015

you can use DateTime.compareTo to perform greater-than-or-equal-to or less-than-or-equal-to checks:

var today = DateTime.now();
var isValid = today.compareTo(timestampValidFrom) >= 0 &&
  today.compareTo(timeStampValidTo) <= 0;

You can define operator <= and operator >= on DateTime as extensions to make this comparison easier to read. package:basics does this for you:

import 'package:basics/basics.dart';

...
var today = DateTime.now();
var isValid = today >= timestampValidFrom && today <= timestampValidTo;

Upvotes: 3

Lo&#239;c Fonkam
Lo&#239;c Fonkam

Reputation: 2340

Use the difference method.

final yesterday = DateTime(now.year, now.month, now.day); // today 12.00.00
final tomorrow = DateTime(now.year, now.month, now.day +1); //tomorrow 12.00.00

int diffInDays = tomorrow.difference(yesterday).inDays;
if (diffInDays == 0){
    //custom code
    print( "same day");
} else if( diffInDays > 0 ) {
    // custom code
    print("tomorrow is greater ");
} else{
    // custom code
    print(" yesterday is less" );
}

Hope it helps!

Upvotes: 2

Midhun MP
Midhun MP

Reputation: 107141

You can simply check whether the current date is between the promotion start date and end date, if yes show the promotion else hide it.

DateTime now = DateTime.now();
DateTime beg = snapshot.data[index].timestampValidFrom.toDate();
DateTime end = snapshot.data[index].timestampValidTo.toDate();
if(now.isAfter(beg) && now.isBefore(end)){
  print('show promo');
} else{
  print('remove promo');
}

It won't include the start & end date. For including the start date, check the following if statement:

if((now.difference(beg).inMinutes >= 0 || now.isAfter(beg)) && (now.isBefore(end) || now.difference(end).inMinutes <= 0)){
  print('show promo');
}else{
  print('remove promo');
}

Upvotes: 1

Related Questions