我的申请遇到了问题。我正在尝试做一些事情来阻止用户选择已经过去的日期和时间。如果用户选择日期和已经过去的时间,将显示错误消息。用户将从datePicker和timePicker中选择日期和时间。有人知道这样做吗?任何帮助将不胜感激。非常感谢!
答案 0 :(得分:2)
您可以阻止用户通过广播接收器ACTION_TIME_CHANGED更改日期时间。如果用户更改日期时间,则会调用广播接收器。覆盖广播接收器中的onRecieve方法。请确保在清单文件中定义广播接收器
@Override
public void onReceive(Context context, Intent intent) {
// You can put conditions the changed date time is not past from the current time and show toast message.
}
答案 1 :(得分:1)
如果您在edittext中设置选择器值,则可以执行以下操作:
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH));
DateFormat df = new SimpleDateFormat(
"dd/MM/yyyy");
Date day_entered, day_valid;
day_entered = df.parse(your_date_edittext.getText()
.toString());
day_valid = df.parse(df.format(cal.getTime()));
if (day_entered.after(day_valid)) {
Toast msg = Toast
.makeText(
Profile.this,
"Please Enter a valid date",
Toast.LENGTH_LONG);
msg.show();
}
答案 2 :(得分:0)
if(fromdate!=null && fromdate.length()>0 && todate!=null && todate.length()>0)
{
try
{
sdf = new SimpleDateFormat("yyyy-mm-dd");
date1 = sdf.parse(fromdate);
date2 = sdf.parse(todate);
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal.setTime(date1);
cal2.setTime(date2);
if(cal.after(cal2)){
System.out.println("Date1 is after Date2");
// Toast.makeText(getApplicationContext(), "from Date1 is after Date2", Toast.LENGTH_SHORT).show();
// clear the dates here........
}
}
catch(Exception e)
{
Log.d("pavan","in exception block ");
}
}