我尝试做一个if-else语句,如果用户输入了过去的时间,它会提醒用户时间已经过去。而且我也无法在用户打开timedialogpicker时将其设置为当前时间。提前感谢。
代码:
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();
}
});
2条答案
按热度按时间pbpqsu0x1#
简而言之:
! LocalTime.of( 10 , 20 ).isBefore( LocalTime.now() )
!
LocalTime#isBefore
java.time
API于2014年3月随Java-8一起发布,取代了error-prone legacy date-time API。从那时起,强烈建议使用这种现代的日期-时间API。您可以使用
LocalTime#of(int hour, int minute)
获取具有给定hour
和minute
值的LocalTime
示例,然后使用LocalTime#isBefore
将其与当前时间(即LocalTime#now
)进行比较。演示:
输出:
!givenTime.isBefore(now)
表示givenTime
等于或晚于now
。从**Trail: Date Time**了解有关现代日期-时间API的更多信息。
ia2d9nvy2#
一种方法是将日历的时间设置为newDate(),然后将小时和分钟设置为选定的值。例如,
然后,您可以使用Java内置的compareTo函数来比较这两个日期。例如: