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

时间:2017-08-29 19:47:29

标签: c# xamarin.android datepickerdialog

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

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

这是我得到的回报......它显示错误的一年和一年出现的月份

如果我注释掉maxdate并注意,那么日历会在正确的年份和月份打开

enter image description here

有人请澄清

1 个答案:

答案 0 :(得分:1)

  

这是我得到的回报......它显示错误的一年和一年出现的月份

     

如果我注释掉maxdate并注意,那么日历会在正确的年份和月份打开

如果您调试代码,您会发现DateTime.Today.Millisecondnew DateTime(today.Year, today.Month - 2, today.Day).Millisecond返回0.这是出错的地方。在Xamarin中,如果你想获得毫秒,你需要做一个DateTime偏移:

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