-2

I have two times, that come from the database. one time is 11:04 AM and another time is 1:00 PM. now how can i compare like this

 if(11:04 AM < 1:00 PM){
   // code is here
  }else{
   //Code is here
   }
Imran Sk
  • 303
  • 5
  • 17

2 Answers2

3

java.time and ThreeTenABP

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);

    String s1 = "11:04 AM";
    String s2 = "1:00 PM";
    LocalTime time1 = LocalTime.parse(s1, timeFormatter);
    LocalTime time2 = LocalTime.parse(s2, timeFormatter);
    if (time1.isBefore(time2)) {
        System.out.println("time1 < time2");
    } else {
        System.out.println("time1 >= time2");
    }

Output from this snippet is:

time1 < time2

The snippet shows how to parse your time strings into LocalTime objects and compare them using isBefore. There are also methods isEqual and isAfter. However, even better. store your times as time datatype in your SQL database and retrieve LocalTime objects directly from your database and avoid the parsing.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

there is no User-defined operator overloading in java . however you can try something like this:

  class mTime{

    int minute , hour;
    public mTime(int hour, int minute){
        this.minute = minute;
        this.hour = hour ;
    }
    public mTime(String time){
        this.hour = Integer.valueOf(time.substring(0,2));
        this.minute = Integer.valueOf(time.substring(3,5));

        if(time.charAt(6) == 'P'){
            hour = hour+12;
        }

    }
    public boolean isBiggerThan(mTime other)
    {
        if(this.hour>other.getHour())
            return true;
        if(this.hour == other.getHour()){
            if(this.minute > other.getMinute())
                return true;
        }
        return false;
    }
    public int getMinute(){
        return minute;
    }
    public int getHour(){
        return hour;
    }
}
mohammad tavakoli
  • 153
  • 1
  • 1
  • 11