最小日期最大日期在 xamarin 中不起作用 android

Min date Max date not working in xamarin android

我正在使用 xamarin android 日期选择器对话框片段。但试图启用今天和 toady + 3 天之间的日期。它不工作。它甚至不适用于最小日期选项。

public static readonly string TAG = "X:" + typeof (DatePickerFragment).Name.ToUpper();
        Action<DateTime> _dateSelectedHandler = delegate { };

        public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            // Note: monthOfYear is a value between 0 and 11, not 1 and 12!
            DateTime selectedDate = new DateTime(year, monthOfYear +1, dayOfMonth);
            Log.Debug(TAG, selectedDate.ToLongDateString());
            _dateSelectedHandler(selectedDate);
        }

        public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
        {
            DatePickerFragment frag = new DatePickerFragment();
            frag._dateSelectedHandler = onDateSelected;
            return frag;
        }

        public override Dialog OnCreateDialog(Bundle savedInstanceState)
        {
            DateTime currently = DateTime.Now;
            DatePickerDialog dialog = new DatePickerDialog(Activity, this, currently.Year, currently.Month - 1,
                                                           currently.Day);

            dialog.DatePicker.MinDate = currently.Millisecond;
            dialog.DatePicker.MinDate = currently.AddDays(3).Millisecond;

            return dialog;
        }

您可以更改 OnCreateDialog 的代码。

 public override Dialog OnCreateDialog(Bundle savedInstanceState)
    {
        DateTime currently = DateTime.Now;
        DatePickerDialog dialog = new DatePickerDialog(Activity,
                                                       this,
                                                       currently.Year,
                                                       currently.Month - 1,
                                                       currently.Day);

       dialog.DatePicker.MinDate = (long)(DateTime.Now.Date - new DateTime(1970, 1, 1)).TotalMilliseconds-1000 * 60 * 60 * 24 * 3;
       dialog.DatePicker.MaxDate = (long)(DateTime.Now.Date - new DateTime(1970, 1, 1)).TotalMilliseconds + 1000 * 60 * 60 * 24 * 3;
        return dialog;
    }

有DatePicker.Note的截图:我设置的最小日期是三天前,最大日期是三天后。

对于不想手动计算范围的开发人员,只是对先前答案的一个小改进。

public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
    DateTime currently = DateTime.Now;
    DatePickerDialog dialog = new DatePickerDialog(Activity,
                                                   this,
                                                   currently.Year,
                                                   currently.Month - 1,
                                                   currently.Day);

    dialog.DatePicker.MinDate = (long)(currently.AddDays(-3) - new DateTime(1970, 1, 1)).TotalMilliseconds;
    dialog.DatePicker.MaxDate = (long)(currently.AddDays(3)  - new DateTime(1970, 1, 1)).TotalMilliseconds;
    return dialog;
}