显示月份前进的DatePickerDialog比其构造函数中设置的(Xamarin.Android)

时间:2018-02-09 10:17:42

标签: xamarin.android datapicker

我声明了以下变量:

private int year = DateTime.Now.Year, month = DateTime.Now.Month, day = DateTime.Now.Day;

我创建了DatePickerDialog:

DatePickerDialog datePickerDialog = new DatePickerDialog(this, this, year, month, day);

当我调用它的方法show:

datePickerDialog.Show();

如果日历必须是今天09.03.2018,则会显示已选中09.02.2018的日历。然后,当我从显示的日历中选择某个日期时,它会从我选择的内容中选择一个月向后的日期,例如,如果我选择10.3.2018它说我已经选择了{{1} } 这是我的所有活动:

10.02.2018

1 个答案:

答案 0 :(得分:1)

  

如果必须是今天09.02.2018的日期,则显示选择了09.03.2018的日历

请检查手机的时间,它可以在手机上使用。

  

如果我选择10.3.2018它说我已经选择了10.02.2018

是的,在OnDateSet方法中,月份从0开始,1月份为0,2月份为1。您需要使用this.month=month+1;,并替换

string selectedDate = String.Format(day + "." + month + "." + year);

string selectedDate = String.Format(day + "." + this.month + "." + year);

更新

正如我所说,月份从0开始,因此您需要-1+1,请根据您的代码查看以下代码。

public class MainActivity : Activity, IOnDateSetListener
{
    private int year = DateTime.Now.Year, month = DateTime.Now.Month-1, day = DateTime.Now.Day;
    Button btnDatePicker;

    //set btnDatePicker's text to be whatever user has selected 
    public void OnDateSet(DatePicker view, int year, int month, int dayOfMonth)
    {
        this.year = year;
        this.month = month+1;
        this.day = dayOfMonth;
        string selectedDate = String.Format(day + "." + this.month + "." + year);
        btnDatePicker.Text = selectedDate;
    }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.Main);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, this, year, month, day);

        //set btnDatePicker's text to be DateTime.Now 
        btnDatePicker = FindViewById<Button>(Resource.Id.btnDatePicker);
        btnDatePicker.Text = DateTime.Now.ToString("dd.MM.yyyy");

        btnDatePicker.Click += delegate
        {
            datePickerDialog.Show();
        };
    }
}