如何在日期选择器对话框中设置最大日期和最小日期

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

我想让日历显示特定的月份,我想在日历中定义允许的日期范围

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

这是我在 return 中得到的...它显示错误的年份和月份

如果我注释掉 maxdate 和 mindate,则日历会在正确的年份和月份打开

有人请澄清

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

如果调试代码,您会发现 DateTime.Today.Millisecondnew DateTime(today.Year, today.Month - 2, today.Day).Millisecond returns 0。这就是问题所在。在Xamarin中,如果你想得到毫秒,你需要做一个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();