How to compare if a string is of less value than other string flutter

3,413

Solution 1

Since you're comparing dates you can use the DateTime class to generate new dates and then use the helper method isBefore to do the comparison. You can also use other helper methods like isAfter and difference

 var now = new DateTime.now();
 var earlier = now.subtract(const Duration(seconds: 5));

  if(earlier.isBefore(now)){
    print('Earlier is 5 seconds before now, so earlier.isBefore(now) is true');
  }

Solution 2

In order to compare dates, you need to do something like this,

    var df1 = DateFormat('dd-MM-yyyy').parse('22-10-2019');
    var df2 = DateFormat('dd-MM-yyyy').parse('25-10-2019');
    print(df1.isBefore(df2).toString());

Output: true


Edit : you will have to use install intl package inside pubspec.yaml to use code above,

dependencies:
  intl: ^0.16.0
Share:
3,413
André Sousa
Author by

André Sousa

Updated on December 16, 2022

Comments

  • André Sousa
    André Sousa over 1 year

    I need help to compare 2 strings that i have and i want to check if one of them has less value than the other so i can throw an alert message. My code is as followed

    if (dateEntered <= date) {
      print("DateEntered wrong $dateEntered");
    }
    

    The error is that

    The operator '<=' isn't defined for the class 'String'. Try defining the operator '<='

    Thank you for your time

    • SRR
      SRR over 4 years
      When you say 'less value' what exactly do you mean? That the amount of characters in the string differ by a certain amount or that the strings don't match entirely?
    • André Sousa
      André Sousa over 4 years
      for example i want to compare 2 dates so i want to see if the entered date isnt before the current day
    • Benjamin
      Benjamin over 4 years
      Use DateTime.parse(String)
    • André Sousa
      André Sousa over 4 years
      Didnt work :( "The operator '<=' isn't defined for the class 'DateTime'. Try defining the operator '<='"
    • Benjamin
      Benjamin over 4 years
      Use the helper methods isBefore and isAfter