2017-08-11 47 views
0

我在这里提供了一个输入信息但代码不起作用的场景。当我输入12/11/2015时,Address2Panel显示了什么。这是错误的,因为没有更多的日期可以输入,因为人A出生在2015年11月12日。该逻辑应输入过去5年的地址。但是,如果出生日期差距不比当前日期的5年时间更短,那就会出错。日期时间和公式改进C#

人生日= 2015年12月11日

某甲StartLiving = 2015年12月11日,因为它的一天,他/她就诞生了。 不应该显示Address2Panel

int CurrentDateInMonths = (((DateTime.Today.Year) * 12) + (DateTime.Today.Month)); 
    static int AlienMonthsAtCurrentAddress = 0; 

     DateTime myDateTime; 
     //LivedHere = 12/11/2015 
     myDateTime = DateTime.Parse(LivedHere.Text); 

     AlienMonthsAtCurrentAddress = (CurrentDateInMonths - (((Convert.ToInt16(myDateTime.Year)) * 12) + Convert.ToInt16(myDateTime.Month))); 
     if (AlienMonthsAtCurrentAddress < 60) 
     { 
      Address2Panel.Visible = true;//shows the Address2Panel 
     } 
     else 
     { 
      ClearAddress2Panel();//hides also the Address2Panel 
     } 

我应该如何提高我的公式和日期时间处理任何建议?

回答

0

无需日期转换成个月,使用DateTime.Subtract方法减去日期:
从MSDN,DateTime.Subtract法减去这个instance.It指定的日期和时间,返回时间跨度对象具有物业Days

static int AlienMonthsAtCurrentAddress = 0; 
try 
{ 

    DateTime myDateTime; 
    myDateTime = DateTime.Parse(LivedHere.Text); 

    // If you don't wish to subtract from today's date use required date in place of DateTime.Now 
    TimeSpan span = DateTime.Now.Subtract (myDateTime); 
    if (span.Days < 60) 
    { 
     Address2Panel.Visible = true;//shows the Address2Panel 
    } 
    else 
    { 
     ClearAddress2Panel();//hides also the Address2Panel 
    } 

} 
catch { } 
+0

感谢您对DateTime操作的想法。但它不能解决我的问题。当人A出生日期= 12/11/2000,并且我把12/11/2015作为LivedHere地址。它没有显示我需要的额外字段。它应该显示出来,因为这个想法是输入过去5年的地址。和12/11/2015不是5年,当前日期是8/11/2017 – Ping

+0

无论日期是什么,使用DateTime.Subtract恕我直言,离开!我编辑了我的答案 – Winnie

0

你可以检查年,月,日与单独的逻辑,然后让他们一起:

DateTime date = new DateTime(2015,11,12) 
DateTime input = getDate() 
int years = input.Year - date.Year - 1 
years += If(input.Month > date.Month, 1, 0) 
years += If(input.Month = date.Month AndAlso input.Day >= date.Day, 1, 0) 

这将输出两天之间的确切年数(截断生成的整数)。你只需要将它与5比较,在你的情况下