How to set maximum date and minmum date in date picker dialog

2.5k Views Asked by At

I would like to make the calendar show particular month and I would like to define range of allowed dates in calendar

DateTime today = DateTime.Today;
DatePickerDialog dateDialog = new DatePickerDialog(this, this.OnToDateSet, today.Year, today.Month - 1, today.Day);
dateDialog.DatePicker.MaxDate = DateTime.Today.Millisecond;
dateDialog.DatePicker.MinDate = new DateTime(today.Year, today.Month - 2, today.Day).Millisecond;
dateDialog.Show();  

this is what I get in return ... it shows the wrong year & month when it appears

if I comment out maxdate and mindate then calendar opens at right year and month

enter image description here

Somebody please clarify

1

There are 1 best solutions below

3
On BEST ANSWER

this is what I get in return ... it shows the wrong year & month when it appears

if I comment out maxdate and mindate then calendar opens at right year and month

If you debug your codes, you will find DateTime.Today.Millisecond and new DateTime(today.Year, today.Month - 2, today.Day).Millisecond returns 0. This is where things went wrong. In Xamarin, if you want to get the Millisecond, you need to do a DateTime offset:

DateTime today = DateTime.Today;
DatePickerDialog dateDialog = new DatePickerDialog(this, this, today.Year, today.Month - 1, today.Day);
//DateTime.MinValue isn't 1970/01/01 so we need to create a min date manually
double maxSeconds = (DateTime.Today - new DateTime(1970, 1, 1)).TotalMilliseconds;
double minSeconds = (new DateTime(today.Year, today.Month - 2, today.Day) - new DateTime(1970, 1, 1)).TotalMilliseconds;
dateDialog.DatePicker.MaxDate = (long)maxSeconds;
dateDialog.DatePicker.MinDate = (long)minSeconds;
dateDialog.Show();