Softlion
Softlion

Reputation: 12615

How to set min and max date in a DatePickerDialog?

I'm trying to set mindate to 1900 and maxdate to 1997 to a DatePickerDialog. But whatever i try, the result on the dialog is not what it should be. The doc says it should be the number of milliseconds since 1970. So this code should work.

What have i missed ?

var dialog = new DatePickerDialog(this, (ss, ee) =>
{
  var dateSelected = ee.Date;
}, model.Birthday.Year, model.Birthday.Month - 1, model.Birthday.Day);


var origin = new DateTime(1970, 1, 1);
dialog.DatePicker.MinDate = 0;// (int)(DateTime.Now.Date.AddYears(-120) - origin).TotalMilliseconds;
dialog.DatePicker.MaxDate = (int)(DateTime.Now.Date.AddYears(-8) - origin).TotalMilliseconds;

Upvotes: 0

Views: 3514

Answers (2)

Hüseyin
Hüseyin

Reputation: 11

  protected override Dialog OnCreateDialog(int id)
        {
            switch (id)
            {
                case DATE_DIALOG_ID:
                    DatePickerDialog dialog = new DatePickerDialog(this, OnDateSet, date.Year, date.Month - 1, date.Day);
                    string _gs = servis.gosterilecekRandevuGunSuresi();
                    int _guns = Convert.ToInt32(_gs);



                    DateTime origin = new DateTime(1970, 1, 1);
                    string tarih = origin.Date.ToString("dd.MM.yyyy");
                    DateTime dt = Convert.ToDateTime(tarih);
                    var datetime = Convert.ToDateTime(tarih);

                    long sayi = (long)(DateTime.Now.Date - origin.Date).TotalMilliseconds;
                    long sayi2 = (long)(DateTime.Now.Date.AddDays(_guns) - origin).TotalMilliseconds;
                    dialog.DatePicker.MinDate = sayi;
                    dialog.DatePicker.MaxDate = sayi2;

                    return dialog;
            }
            return null;
        }

Upvotes: 1

Aaron He
Aaron He

Reputation: 5549

The problem is TotalMilliseconds exceeds the max value an int can hold.

So, cast it to long will be fine which is actually what DatePicker.MaxDate expects.

dialog.DatePicker.MaxDate = (long)(DateTime.Now.Date.AddYears(-8) - origin).TotalMilliseconds;

Upvotes: 3

Related Questions