Datetimepicker条件语句visual basic

时间:2014-02-19 15:21:15

标签: vb.net visual-studio-2013

似乎我在研究和理解代码。如果检测到轻微的话,它就不会顺从。从2014年到上面的地方没有错误,但2014年及以下出现了错误。

我想知道如何以正确的方式根据今天的日期进行测试,以便在我放入1993年时允许进行测试。

假设我将使用工具箱中的datetimepicker。

If (DateTime.Now.Subtract(Birthdate.Value.AddYears(18)). TotalDays >= 0)

我不确定这是否是正确的代码方式。

1 个答案:

答案 0 :(得分:0)

这会告诉你是否有人超过18岁

' underage person (roughly 16 years old)
Dim birthday1 As New DateTime(DateTime.Now.Year - 16, 2, 15)
' person's 18th birthday is today
Dim birthday2 = New DateTime(DateTime.Now.Year - 18, DateTime.Now.Month, DateTime.Now.Day)
' roughly 20 year old person
Dim birthday3 As New DateTime(DateTime.Now.Year - 20, 10, 6)
' method 1 using all DateTime functions
Debug.Print(birthday1.AddYears(18).CompareTo(DateTime.Now)) ' 1
Debug.Print(birthday2.AddYears(18).CompareTo(DateTime.Now)) ' -1
Debug.Print(birthday3.AddYears(18).CompareTo(DateTime.Now)) ' -1
' method 2
Debug.Print(DateTime.Now.Subtract(birthday1.AddYears(18)).Days >= 0) ' false
Debug.Print(DateTime.Now.Subtract(birthday2.AddYears(18)).Days >= 0) ' true
Debug.Print(DateTime.Now.Subtract(birthday3.AddYears(18)).Days >= 0) ' true

就个人而言,我会将其放在DateTime

的扩展方法中
Module ExtensionMethods

    <Extension()>
    Public Function IsOlderThan(dt As DateTime, age As Integer) As Boolean
        Return dt.AddYears(age).CompareTo(DateTime.Now) = -1
    End Function

End Module

用法:

Dim isOfAge = birthday.IsOlderThan(18) ' true or false