如何防止用户设置早于当前日期和时间的日期和时间

3

我的应用程序遇到了一个问题。我想要做的是防止用户选择已经过去的日期和时间。如果用户选择了已经过去的日期和时间,将会显示错误消息。用户将从日期选择器和时间选择器中选择日期和时间。有没有任何关于如何实现这个功能的想法?非常感谢您提供的任何帮助!谢谢!

3个回答

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
如果您正在编辑文本中设置选择器的值,可以这样做:
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();
                                    }

嗨,你说的在edittext中设置picker值是什么意思?我直接从pickers中设置值。 - CallMyName
您是否将从选择器获取的值设置到类似于EditText、TextView或其他控件中的某个位置? - Manoj Kumar
哦,是的,我将选择器中的值传递到文本视图中。 - CallMyName
然后在我的代码中,您可以传递该值而不是your_date_edittext.getText().toString());,或者您可以简单地使用setmindate()函数 :P - Manoj Kumar
请查看此链接:https://dev59.com/B1TTa4cB1Zd3GeqPpyk4 - Manoj Kumar
显示剩余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 ");
      }

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接