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
}
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
}
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.
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).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;
}
}