如何在 android 的 datepicker 对话框中设置最大日期?

Posted

技术标签:

【中文标题】如何在 android 的 datepicker 对话框中设置最大日期?【英文标题】:How set maximum date in datepicker dialog in android? 【发布时间】:2013-05-20 21:42:29 【问题描述】:

在我的应用程序中,我使用日期选择器来设置日期。我想根据系统日期设置日期选择器的最大日期为今天的日期。我不知道如何将日期选择器的最大日期设置为今天的日期。任何人都可以知道帮我解决这个问题。

我的日期选择器编码是:

private int pYear;
private int pMonth;
private int pDay;
static final int DATE_DIALOG_ID = 0;

final Calendar c = Calendar.getInstance();
pYear = c.get(Calendar.YEAR);
pMonth = c.get(Calendar.MONTH);
pDay = c.get(Calendar.DAY_OF_MONTH);

// Date picker
public Dialog onCreateDialog(int id) 
    switch (id) 
    case DATE_DIALOG_ID:

        DatePickerDialog.OnDateSetListener pDateSetListener = new DatePickerDialog.OnDateSetListener() 

            public void onDateSet(DatePicker view, int year,
                    int monthOfYear, int dayOfMonth) 

                pYear = year;
                pMonth = monthOfYear;
                pDay = dayOfMonth;

                e_dob.setText(new StringBuilder()
                        // to set date in editext
                        .append(pDay).append("/").append(pMonth + 1)
                        .append("/").append(pYear).append(" "));
            
        ;
        return new DatePickerDialog(this, pDateSetListener, pYear, pMonth,
                pDay);

    
    return null;

【问题讨论】:

【参考方案1】:

使用setMaxDate()

例如,将return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay) 语句替换为如下内容:

    DatePickerDialog dialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
    dialog.getDatePicker().setMaxDate(new Date().getTime());
    return dialog;

【讨论】:

你的回答也值得一票;),你展示了捷径! 要为所有 api 设置最大日期试试这个gist.github.com/Kishanjvaghela/7b8738bbb224c5f2e652 设置 datePicker 的setMaxDate 后,setMaxDate 总是高亮选中,这里是image @hasnain_ahmad 是的,我也意识到了这一点,但我还没有找到解决方案。【参考方案2】:

获取今天的日期(和时间)并将其应用为最大日期。

Calendar c = Calendar.getInstance();
c.set(2017, 0, 1);//Year,Mounth -1,Day
your_date_picker.setMaxDate(c.getTimeInMillis());

我们也可以这样做(查看*** answer 了解 System.currentTimeMillis() 与 Calendar 方法)

long now = System.currentTimeMillis() - 1000;
dp_time.setMinDate(now);
dp_time.setMaxDate(now+(1000*60*60*24*7)); //After 7 Days from Now

【讨论】:

请添加一些关于代码在做什么的解释。 这是设置任何最大日期的完美且实际的答案 我正在寻找这也适用的最小日期。谢谢! 什么是c.set(2017, 0, 1)?这是最早的日期吗?【参考方案3】:

您可以尝试替换此行:

return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);

由那些:

DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();

Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date
return dpDialog;

【讨论】:

【参考方案4】:

试试这个

我尝试了太多的解决方案,但都没有工作,浪费了我半天的时间,我终于找到了一个解决方案。

这段代码只是向您展示了一个 DatePickerDialog,其中包含最小和最大日期、月份和年份,您可以随意修改它。

final Calendar calendar = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() 
                    @Override
                    public void onDateSet(DatePicker arg0, int year, int month, int day_of_month) 
                        calendar.set(Calendar.YEAR, year);
                        calendar.set(Calendar.MONTH, (month+1));
                        calendar.set(Calendar.DAY_OF_MONTH, day_of_month);
                        String myFormat = "dd/MM/yyyy";
                        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
                        your_edittext.setText(sdf.format(calendar.getTime()));
                    
                ,calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());// TODO: used to hide previous date,month and year
                calendar.add(Calendar.YEAR, 0);
                dialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());// TODO: used to hide future date,month and year
                dialog.show();

输出:- 禁用以前和将来的日历

【讨论】:

粘贴代码时出现错误 - getActivity() 为红色。错误是“找不到符号方法 getActivity()”。建议创建方法或创建属性。 想通了 - 这是我们调用的活动。如果 DatePickerDialog 的语法显示在 cmets 中,那将会很有帮助。支持这个答案 @SriramNadiminti getActivity() 是一个上下文,如果您在 Activity 中使用,则可以使用“this”,而对于 Fragment,请使用“getActivity()” 谢谢。如何将数据传递给公共 Int 变量“MyDate”、“MyMonth”和“MyYear”?我必须单击两次才能使 setText 工作【参考方案5】:
private int pYear;
private int pMonth;
private int pDay;
static final int DATE_DIALOG_ID = 0;

/**inside oncreate */
final Calendar c = Calendar.getInstance();
         pYear= c.get(Calendar.YEAR);
         pMonth = c.get(Calendar.MONTH);
         pDay = c.get(Calendar.DAY_OF_MONTH);


 @Override
     protected Dialog onCreateDialog(int id) 
             switch (id) 
             case DATE_DIALOG_ID:
                     return new DatePickerDialog(this,
                             mDateSetListener,
                             pYear, pMonth-1, pDay);
            

             return null;
     
     protected void onPrepareDialog(int id, Dialog dialog) 
             switch (id) 
             case DATE_DIALOG_ID:
                     ((DatePickerDialog) dialog).updateDate(pYear, pMonth-1, pDay);
                     break;
             
        
     private DatePickerDialog.OnDateSetListener mDateSetListener =
         new DatePickerDialog.OnDateSetListener() 
         public void onDateSet(DatePicker view, int year, int monthOfYear,
                         int dayOfMonth) 
                // write your code here to get the selected Date
         
 ;

试试这个应该可以的。谢谢

【讨论】:

【参考方案6】:

直接在main方法中使用这段代码希望对你有帮助...

@RequiresApi(api = Build.VERSION_CODES.N)       
public DatePickerDialog datePickerDialog_db()


    DatePickerDialog pickerDialog = new DatePickerDialog(getApplicationContext(),your view, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
    myCalendar.get(Calendar.DAY_OF_MONTH));

    pickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());

    pickerDialog.show();

    return null;       

【讨论】:

【参考方案7】:

这是一个 Kotlin 扩展函数:

fun EditText.transformIntoDatePicker(context: Context, format: String, maxDate: Date? = null) 
    isFocusableInTouchMode = false
    isClickable = true
    isFocusable = false

    val myCalendar = Calendar.getInstance()
    val datePickerOnDataSetListener =
        DatePickerDialog.OnDateSetListener  _, year, monthOfYear, dayOfMonth ->
            myCalendar.set(Calendar.YEAR, year)
            myCalendar.set(Calendar.MONTH, monthOfYear)
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            val sdf = SimpleDateFormat(format, Locale.UK)
            setText(sdf.format(myCalendar.time))
        

    setOnClickListener 
        DatePickerDialog(
            context, datePickerOnDataSetListener, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
            myCalendar.get(Calendar.DAY_OF_MONTH)
        ).run 
            maxDate?.time?.also  datePicker.maxDate = it 
            show()
        
    

用法:

活动中:

editText.transformIntoDatePicker(this, "MM/dd/yyyy")
editText.transformIntoDatePicker(this, "MM/dd/yyyy", Date())

在片段中:

editText.transformIntoDatePicker(requireContext(), "MM/dd/yyyy")
editText.transformIntoDatePicker(requireContext(), "MM/dd/yyyy", Date())

【讨论】:

【参考方案8】:

查看我的自定义日期选择器对话框

https://github.com/Redman1037/EightFoldsDatePickerDialog

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;


/**
 * Created by Manohar on 14/08/2017.
 */

public class EightFoldsDatePickerDialog extends DatePickerDialog 


    private DatePickerDialog datePickerDialog;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");

    @RequiresApi(api = Build.VERSION_CODES.N)
    public EightFoldsDatePickerDialog(@NonNull Context context) 
        super(context);
        datePickerDialog = new DatePickerDialog(context);

    

    @RequiresApi(api = Build.VERSION_CODES.N)
    public EightFoldsDatePickerDialog(@NonNull Context context, int themeResId) 
        super(context, themeResId);
        datePickerDialog = new DatePickerDialog(context, themeResId);
    

    public EightFoldsDatePickerDialog(@NonNull Context context, @Nullable OnDateSetListener listener, int year, int month, int dayOfMonth) 
        super(context, listener, year, month, dayOfMonth);
        datePickerDialog = new DatePickerDialog(context, listener, year, month, dayOfMonth);

    

    public EightFoldsDatePickerDialog(@NonNull Context context, int themeResId, @Nullable OnDateSetListener listener, int year, int monthOfYear, int dayOfMonth) 
        super(context, themeResId, listener, year, monthOfYear, dayOfMonth);
        datePickerDialog = new DatePickerDialog(context, themeResId, listener, year, monthOfYear, dayOfMonth);
    

    public void show() 
        datePickerDialog.show();
    


    public void setMinDate(int year, int month, int day) 

        String minDate = "" + day + "-" + getmonth(month) + "-" + year;

        try 
            datePickerDialog.getDatePicker().setMinDate(dateFormat.parse(minDate).getTime());
         catch (ParseException e) 
            e.printStackTrace();
        

    

    public void setMaxDate(int year, int month, int day) 

        String maxDate = "" + day + "-" + getmonth(month) + "-" + year;
        try 
            datePickerDialog.getDatePicker().setMaxDate(dateFormat.parse(maxDate).getTime());
         catch (ParseException e) 
            e.printStackTrace();
        

    

    public void setTodayAsMaxDate() 

        datePickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTime().getTime());

    

    public void setTodayAsMinDate() 

        datePickerDialog.getDatePicker().setMinDate(Calendar.getInstance().getTime().getTime());

    


    private String getmonth(int month) 

        switch (month) 
            case 1:
                return "January";

            case 2:
                return "February";

            case 3:
                return "March";

            case 4:
                return "April";

            case 5:
                return "May";

            case 6:
                return "June";

            case 7:
                return "July";

            case 8:
                return "August";

            case 9:
                return "September";

            case 10:
                return "October";

            case 11:
                return "November";

            case 12:
                return "December";


        
        return "January";

    


用法

将EightFoldsDatePickerDialog.java 复制到您的项目中

EightFoldsDatePickerDialog datePickerDialog=new EightFoldsDatePickerDialog(this, new DatePickerDialog.OnDateSetListener() 
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) 
              //Do something with date
                Toast.makeText(this, "Year "+year+" month "+month+" day "+dayOfMonth, Toast.LENGTH_SHORT).show();
            
        ,year,month,day);   // give any  year , month , day values, this will be opened by default in dialog

        datePickerDialog.setMinDate(2017,8,7); //arguments are   year , month , date (use for setting custom min date)
        datePickerDialog.setMaxDate(2017,8,25);  //arguments are   year , month , date (use for setting custom max date)

       // datePickerDialog.setTodayAsMinDate();   // sets today's date as min date
       // datePickerDialog.setTodayAsMaxDate();    // sets today's date as max date

        datePickerDialog.show();

结果

【讨论】:

【参考方案9】:

private void selectDOB()

    final Calendar calendar = Calendar.getInstance();
    mYear = calendar.get(Calendar.YEAR);
    mDay = calendar.get(Calendar.DATE);
    mMonth = calendar.get(Calendar.MONTH);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() 
        @SuppressLint("LongLogTag")
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) 
            strDateOfBirth = (month + 1) + "-" + dayOfMonth + "-" + year;

            //********************** check and set date with append 0 at starting***************************
            if (dayOfMonth < 10) 
                strNewDay = "0" + dayOfMonth;
             else 
                strNewDay = dayOfMonth + "";
            
            if (month + 1 < 10) 
                strNewMonth = "0" + (month + 1);
             else 
                strNewMonth = (month + 1) + "";
            

            Log.e("strnewDay *****************", strNewDay + "");
            Log.e("strNewMonth *****************", strNewMonth + "");

            //    etDateOfBirth.setText(dayOfMonth + " / " + (month + 1) + " / " + year);
            etDateOfBirth.setText(strNewDay + " / " + strNewMonth + " / " + year);

            Log.e("strDateOfBirth *******************", strDateOfBirth + "");

        
    , mYear, mMonth, mDay);

    datePickerDialog.show();

    //*************** input date of birth must be greater than or equal to 18 ************************************

    Calendar maxDate = Calendar.getInstance();
    maxDate.set(Calendar.DAY_OF_MONTH, mDay);
    maxDate.set(Calendar.MONTH, mMonth);
    maxDate.set(Calendar.YEAR, mYear - 18);
    datePickerDialog.getDatePicker().setMaxDate(maxDate.getTimeInMillis());

    //*************** input date of birth must be less than today date ************************************
    //   datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());


【讨论】:

您能否添加一些解释您在这里所做的事情以及它与原始代码有何不同?您可能也不希望注释掉的代码或错误日志。 在此用户可以根据其应用程序所需的年龄标准设置日期。就像用户只能将年龄设置在 18 岁以上,那么他可以使用此代码。 getInstance 是 API30。如果我想使用 API 25 及以下版本怎么办?【参考方案10】:
      Calendar cal = Calendar.getInstance();
      datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
    //To set make max 7days date selection on current year and month
    datePickerDialog.getDatePicker().setMaxDate((cal.getTimeInMillis())+(1000*60*60*24*6));

    datePickerDialog.setTitle("Select Date");
    datePickerDialog.show();

【讨论】:

【参考方案11】:

您可以创建Custom date picker,它适用于所有 api 级别。

public class CustomDatePickerDialog extends DatePickerDialog 

    int maxYear;
    int maxMonth;
    int maxDay;

    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) 
        super(context, callBack, year, monthOfYear, dayOfMonth);
    

    public void setMaxDate(long maxDate) 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) 
            getDatePicker().setMaxDate(System.currentTimeMillis());
         else 
            final Calendar c = Calendar.getInstance();
            c.setTimeInMillis(maxDate);
            maxYear = c.get(Calendar.YEAR);
            maxMonth = c.get(Calendar.MONTH);
            maxDay = c.get(Calendar.DAY_OF_MONTH);
        
    

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) 
            super.onDateChanged(view, year, monthOfYear, dayOfMonth);
         else 
            if (year > maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (monthOfYear > maxMonth && year == maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                view.updateDate(maxYear, maxMonth, maxDay);
        
    

设置最大日期

final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(getActivity(),
        myDateListener, year, month, day);
pickerDialog.setMaxDate(System.currentTimeMillis());
pickerDialog.show();

【讨论】:

【参考方案12】:

我通过关注解决了这个问题

final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
    datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());    

希望对你有帮助

【讨论】:

【参考方案13】:
DatePicker dp = (DatePicker) findViewById(R.id.datePicker1);

dp.setMaxDate(new Date().getTime());

【讨论】:

以上是关于如何在 android 的 datepicker 对话框中设置最大日期?的主要内容,如果未能解决你的问题,请参考以下文章

如何从 Android 中的 DatePicker 小部件中获取日期?

Android:如何设置 DatePicker 的样式?

如何在 android 的 datepicker 对话框中设置最大日期?

如何在 Android DatePicker 中设置最小和最大日期?

如何获得MONTHS,DAYS和周(android datepicker)

如何使用 DatePicker 和 TimePicker (Android Studio) 在数据库中存储日期和时间?