Android 如何防止用户设置当前日期和时间之前的日期和时间
我的申请遇到了一个问题。我试图做一些事情来阻止用户选择已经过去的日期和时间。如果用户选择日期和过去的时间,将显示错误消息。用户将从日期选择器和时间选择器中选择日期和时间。有人知道怎么做吗?任何帮助都将不胜感激。非常感谢 如果要在edittext中设置选择器值,可以执行以下操作:Android 如何防止用户设置当前日期和时间之前的日期和时间,android,date,time,datepicker,timepicker,Android,Date,Time,Datepicker,Timepicker,我的申请遇到了一个问题。我试图做一些事情来阻止用户选择已经过去的日期和时间。如果用户选择日期和过去的时间,将显示错误消息。用户将从日期选择器和时间选择器中选择日期和时间。有人知道怎么做吗?任何帮助都将不胜感激。非常感谢 如果要在edittext中设置选择器值,可以执行以下操作: Calendar cal = Calendar.getInstance(); cal.set(cal.get(Calendar.YEAR),
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();
}
您可以通过广播接收器动作\u time\u CHANGED防止用户更改日期时间。如果用户更改日期时间,则将调用广播接收器。覆盖广播接收器中的OnReceive方法。请确保在清单文件中定义广播接收器
@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.
}
}Hi,呃,在edittext中设置选择器值是什么意思?我直接从选择器设置值。您是在设置从选择器获取的值,比如edittext、textview还是什么?哦,是的,我将值从选择器传递到textview。然后在我的代码中,您将该值传递到我的代码中,而不是
your_date_edittext.getText().toString())
或者您可以简单地使用setmindate()
函数:p请参见
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 ");
}