我在检查设置的时间是否超过当前时间后,尝试从TimePicker
中的TextView
对话框设置时间。我从字符串TimePicker
中的s
中选择时间并以(hh:mm)
格式对其进行解析。我使用了SimpleDateFormat.parse("hh:mm")
,但它比较了1970年和今天的日期和时间。
所以我尝试了SimpleDateFormat("dd-mm-yy hh:mm:ss.SSS").parse(s);
以及日期,月份和年份,但它给了我ParseException
。我使用before()
来检查所选时间是否在当前时间之前。但是我应该首先解析与日期和时间一起设置的时间来使用该方法。如何检查TimePicker
中设置的时间是否小于当前时间。
这就是我的尝试:
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar datetime = Calendar.getInstance();
Calendar c = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime.set(Calendar.MINUTE, minute);
String s = c.get(Calendar.DAY_OF_WEEK) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.YEAR) + " " + String.valueOf((datetime.get(Calendar.HOUR_OF_DAY)) + ":" + datetime.get(Calendar.MINUTE) + ":" + datetime.get(Calendar.SECOND));
try {
Date d = new SimpleDateFormat("dd-mm-yy hh:mm:ss.SSS").parse(s);
Date date = c.getTime();
if (d.before(c.getTime())) {
DateTimePicker.setBooleanDateCheckForTimePicker(false);
Toast.makeText(getActivity(), "Enter valid time", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
String strHrsToShow = (datetime.get(Calendar.HOUR) == 0) ? "12" : datetime.get(Calendar.HOUR) + "";
boolean b = new DateTimePicker().booleanDateCheckForTimePicker;
if (new DateTimePicker().booleanDateCheckForTimePicker) {
timePicker.setText(strHrsToShow + ":" + datetime.get(Calendar.MINUTE) + " " + am_pm);
}
//timePicker.setText(hourOfDay + " "+minute);
}
}
答案 0 :(得分:7)
只是比较时间戳。
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar datetime = Calendar.getInstance();
Calendar c = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime.set(Calendar.MINUTE, minute);
if(datetime.getTimeInMillis() > c.getTimeInMillis()){
// it's after current
}else{
// it's before current'
}
}
答案 1 :(得分:2)
不是使用Date进行比较,而是可以像这样手动检查:
var isBefore=false;
if(hourOfDay < datetime.get(Calendar.HOUR_OF_DAY))
isBefore=true;
else if(hourOfDay == datetime.get(Calendar.HOUR_OF_DAY)){
if(minute < datetime.get(Calendar.MINUTE))
isBefore=true;
}