减少日期更改日期

时间:2018-10-31 07:29:04

标签: c# winforms datepicker

我在WinForm中使用了两个 DatePicker ,并试图做一件简单的事情。每当我尝试选择日期时,说开始日期,然后将结束日期减少一年。但是有条件例如,如果开始日期 为“ 10-12-2018”,则结束日期应为“ 10-12-2017”。同样,如果开始日期为'10 -12-2017',则结束日期将为'10 -12-2016'。同样,如果开始日期为'10 -14-2017',则结束日期将为'10 -12-2016'。因为日期是更改的,而不是年份。

我尝试过反之亦然,这意味着通过 DatePicker 值更改事件增加了年份,并且与 以下:

public frmDetails()
{
   InitializeComponent();
   dtPickerEnd.Value = dtPickerEnd.Value.AddYears(1); //By default adding one year for end date
}

更改开始日期时:

private void dtPickerStart_ValueChanged(object sender, EventArgs e)
{
   if (dtPickerStart.Value.Year == dtPickerEnd.Value.Year) //If year is same, then increase year by one
   {
      dtPickerEnd.Value = dtPickerEnd.Value.AddYears(1);
   }
} 

当我增加开始日期时它起作用,但是当我相反时它不起作用。就像开始日期是'10 -12-2018'一样,结束日期应该是'10 -12-2019'。同样,如果开始日期为'10 -12-2017',则结束日期为'10 -12-2018'。但是现在,我愿意坚持不断减少的一年。不幸的是,我没有得到预期的结果:

private void dtPickerStart_ValueChanged(object sender, EventArgs e)
{
   if (dtPickerStart.Value.Year == dtPickerEnd.Value.Year) //If year is same, then increase year by one
   {
      dtPickerEnd.Value = dtPickerEnd.Value.AddYears(-1);
   }
} 

2 个答案:

答案 0 :(得分:1)

尝试这个

我已经尝试并且成功了

    try
    {
    dateTimePicker2.Value = new DateTime(dateTimePicker1.Value.Year - 1, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day);
    }
    catch
    {
     if(dateTimePicker1.Value.Month==2 && dateTimePicker1.Value.Day==29)
     {
       dateTimePicker2.Value = new DateTime(dateTimePicker1.Value.Year - 1, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day-1);
     }
  }

答案 1 :(得分:1)

public frmDetails()
{
    InitializeComponent();
    oldStartYear = dtPickerStart.Value.Year;
    dtPickerEnd.Value = dtPickerStart.Value.AddYears(1); // or -1
}

private int oldStartYear;

private void dtPickerStart_ValueChanged(object sender, EventArgs e)
{ 
    if (oldStartYear != dtPickerStart.Value.Year)
    {
        oldStartYear = dtPickerStart.Value.Year;
        dtPickerEnd.Value = dtPickerStart.Value.AddYears(1); // or -1
    }
}