Compare time in Java
Most of the time we need to compare two date and date-time objects. Date comparison is required when we want to get the data of some specific date and time from the database or to filter the returned data based on date and time.
In order to compare time, we use the compareTo() method of the LocalTime class. The compareTo() method of the class compares two LocalTime objects. The first LocalTime object is one which we want to compare, and the second object is which we pass to the compareTo() method as a parameter and from which we want to compare this LocalTime object.
Syntax:
The compareTo() method of the LocalTime class
Parameters:
It accepts only a single parameter, i.e., the LocalTime object, which is going to be compared, and it should not be null.
Returns:
The compareTo() method returns three values based on the comparison of the objects:
- It returns a positive value when this LocalTime object is greater than the specified LocalTime object.
- It returns a negative value when this LocalTime object is smaller than the specified LocalTime object.
- It returns zero when this LocalTime object is equal to the specified LocalTime object.
Let's take some examples to understand how the compareTo() method is used for the comparison of two LocalTime objects.
DateFormat like below...
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date inTime = sdf.parse("11:00");
Date outTime = sdf.parse("10:00");
if(inTime.compareTo(outTime) > 0){
Toast.makeText(this, "Out time should be greater than In time", Toast.LENGTH_SHORT).show();
}
EXAMPLE:
String inputfrom_tm = txtfrom_tm.getText().toString();
if (inputfrom_tm.matches("")) {
Toast.makeText(apply.this, "You did not enter From Time", Toast.LENGTH_SHORT).show();
return;
}
String inputto_tm = txtto_tm.getText().toString();
if (inputto_tm.matches("")) {
Toast.makeText(apply.this, "You did not enter To Time", Toast.LENGTH_SHORT).show();
return;
}
// Toast.makeText(getApplicationContext(),inputPhone+inputvisit_purpose+inputvist_detail+inputid_no+inputfrom_dt+inputto_dt+inputtotal_person , Toast.LENGTH_SHORT).show();
Date inTime = sdf.parse(inputfrom_tm);
Date outTime = sdf.parse(inputto_tm);
if(inTime.compareTo(outTime) > 0){
Toast.makeText(this, "Out time should be greater than In time", Toast.LENGTH_LONG).show();
}
else
{
InsertData(NAME, COMPANY_NAME, inputPhone, inputvisit_purpose, inputpurpose_detail, inputid_type, inputid_no, inputfrom_dt, inputto_dt, inputfrom_tm, inputto_tm, inputtotal_person, inputspinner);
}
Post a Comment
0Comments