I'm trying to make a if-else statement that if user put time which have past, it will alert the user that the time has past. And I also unable to set the timedialogpicker to the current time when the user open it. Thanks in advance.
The code:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar timeNow = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
int currHour = calendar.get(Calendar.HOUR_OF_DAY);
int currMin = calendar.get(Calendar.MINUTE);
Time currTime = new Time(currHour, currMin); //This part display error
if (currTime.getTimeInMillis() >= timeNow.getTimeInMillis()) { //This part display error
//it's after current
int hour = hourOfDay % 12;
} else {
//it's before current'
Toast.makeText(getApplicationContext(), "Invalid Time", Toast.LENGTH_LONG).show();
}
time = "";
time = hourOfDay+":"+minute;
Userbook book = new Userbook(temp, time);
db.collection("Booking").add(book).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(MainActivity.this, "Time is "+currHour+":"+currMin, Toast.LENGTH_SHORT).show();
}
},timeNow.get(Calendar.HOUR_OF_DAY), timeNow.get(Calendar.MINUTE),false);
timePickerDialog.show();
}
});
In brief: ! LocalTime.of( 10 , 20 ).isBefore( LocalTime.now() )
LocalTime#isBefore
The java.time
API, released with Java-8 in March 2014, supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API.
You can use LocalTime#of(int hour, int minute)
to get an instance of LocalTime
with the given hour
and minute
values and then compare it with the current time (i.e. LocalTime#now
) using LocalTime#isBefore
.
Demo:
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
// Sample hour and minute values
int hour = 10;
int minute = 20;
LocalTime givenTime = LocalTime.of(hour, minute);
System.out.println(!givenTime.isBefore(now));
}
}
Output:
false
!givenTime.isBefore(now)
means givenTime
is either equal to or after now
.
Learn more about the modern Date-Time API from Trail: Date Time.