如何在DatePickerDialog中设置最小日期,具体日期不是今天(XAMARIN)

时间:2017-05-05 09:38:32

标签: c# android xamarin android-datepicker datepickerdialog

我想要的是在要禁用的特定日期之前设置日期(而不是在今天之前)。例如:

今天是2017年5月5日 具体目标日期:仅限5月1日至5月5日。

使用此代码

禁用超过这一天的所有内容
        dialog.DatePicker.MaxDate = Java.Lang.JavaSystem.CurrentTimeMillis();

但是我无法在5月1日之前和之前禁用它。

我现在有这个代码。

public class DatePickerFragment : DialogFragment,
                              DatePickerDialog.IOnDateSetListener
{
    // TAG can be any string of your choice.
    public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();

    // Initialize this value to prevent NullReferenceExceptions.
    Action<DateTime> _dateSelectedHandler = delegate { };

    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);

        //****************this is my problem*****************//
        dialog.DatePicker.MinDate = CurrentUser.lastReplenish.Millisecond;
        dialog.DatePicker.MaxDate = Java.Lang.JavaSystem.CurrentTimeMillis();
        //***************************************************//
        return dialog;
    }

    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);
    }
}

1 个答案:

答案 0 :(得分:1)

我猜“CurrentUser.lastReplenish”是一个.NET DateTime对象?! Android总是需要从1970年1月1日(纪元)开始的毫秒,所以你需要计算一下:

dialog.DatePicker.MinDate = (long)CurrentUser.lastReplenish.ToUniversalTime()
    .Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds;