jace
jace

Reputation: 1674

How to set min date in DatePickerDialog with a specific date not today (XAMARIN)

What I want is to set date before specific date to be disabled (not before today). e.g. :

Today is May 5, 2017 Target Specific Date: May 1 - May 5 only.

All greater than this day is disabled using this code

        dialog.DatePicker.MaxDate = Java.Lang.JavaSystem.CurrentTimeMillis();

But I can't disable from May 1 and before it.

I have this code for now.

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

I

Upvotes: 0

Views: 1153

Answers (1)

Malte G
Malte G

Reputation: 792

I guess "CurrentUser.lastReplenish" is a .NET DateTime object?! Android always needs the milliseconds starting from January 1 1970 (epoch), so you need to calculate a bit:

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

Upvotes: 1

Related Questions