Vb.net 如何以编程方式计算下一个生日

Vb.net 如何以编程方式计算下一个生日,vb.net,Vb.net,我有一个带有出生日期列的数据表 我想将日期分开,并将年份部分改为今天。年份即当前年份 下面是我的代码: Dim birthda As New SqlDataAdapter(birthcmd) Dim birthdt As New DataTable birthda.Fill(birthdt) For Each rw As DataRow In birthdt.Rows Dim dob As String = rw.Item(3) Dim mdat As Date = Form

我有一个带有出生日期列的数据表

我想将日期分开,并将年份部分改为今天。年份即当前年份

下面是我的代码:

Dim birthda As New SqlDataAdapter(birthcmd)
Dim birthdt As New DataTable
birthda.Fill(birthdt)

For Each rw As DataRow In birthdt.Rows
    Dim dob As String = rw.Item(3)

    Dim mdat As Date = FormatDateTime(dob, DateFormat.ShortDate)

    Dim bday As Date = (Date.Today.Year & mdat.Month & mdat.Day)

    Dim yers As Integer = DateDiff(DateInterval.Year, mdat.Date, Today.Date)
    Dim moths As Integer = DateDiff(DateInterval.Month, mdat.Date, Today.Date)
    Dim dys As Integer = DateDiff(DateInterval.Day, mdat.Date, Today.Date)
但我得到了这个错误:

从字符串“2019715”到类型“Date”的转换无效。 描述:执行当前web请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误的更多信息以及错误在代码中的起源

异常详细信息:System.InvalidCastException:从字符串“2019715”转换为类型“Date”无效

源错误:
第149行:
第150行:Dim bday As Date=(Date.Today.Year&mdat.Month&mdat.Day)


在字符串到日期的转换方面,VB.net非常独特

我建议将各个组件的日期转换为如下:

Dim bday as Date = New Date(Date.Today.Year, mdat.Month, mdat.Day)
或者如评论中所述,尝试使用VB.Net DateTime

Dim bday as New DateTime(Date.Today.Year, mdat.Month, mdat.Day, 0, 0, 0)

谢谢我想我已经明白了这就是我所做的。我计算了当前年份的年龄,并将结果添加到出生日期的年份部分。
这是密码

对于birthdt.行中的每个rw作为数据行

        Dim dob As DateTime = rw.Item(2)


        Dim mdat As Date = FormatDateTime(dob, DateFormat.ShortDate)

     Dim yers As Integer = DateDiff(DateInterval.Year, mdat.Date, Today.Date)
        Dim moths As Integer = DateDiff(DateInterval.Month, mdat.Date, Today.Date)

        Dim dys As Integer = DateDiff(DateInterval.Day, mdat.Date, Today.Date)

        Dim ndob As Date = (DateAdd(DateInterval.Year, yers, mdat))

        Dim yers2 As Integer = DateDiff(DateInterval.Year, ndob.Date, Today.Date)
        Dim moths2 As Integer = DateDiff(DateInterval.Month, ndob.Date, Today.Date)
        Dim dys2 As Integer = DateDiff(DateInterval.Day, ndob.Date, Today.Date)     

我是基于你在一篇文章中所写的:

想要查看那些在某一周即将迎来生日的人

处理闰年和可能在明年的日期是很麻烦的,但我想我已经把所有的情况都包括在这里了

我在SQLServer中创建了一个表“Pets”,其中包含“Name”和“DOB”列,并在其中放入了一些数据

我创建了一个新的Windows窗体项目,并在Form1中添加了一个多行文本框,并使用了以下代码:

Imports System.Data.SqlClient
Imports System.Text

Public Class Form1

    Sub ShowUpcomingBirthdays()
        Dim csb As New SqlConnectionStringBuilder With {.DataSource = ".\SQLEXPRESS", .InitialCatalog = "Testing", .IntegratedSecurity = True}

        Dim birthdt As New DataTable()

        Dim sql = "SELECT [Name], [DOB] FROM [Pets]"

        Using conn As New SqlConnection(csb.ConnectionString)
            Using sqlCmd As New SqlCommand(sql, conn)
                Dim da As New SqlDataAdapter With {.SelectCommand = sqlCmd}
                da.Fill(birthdt)
            End Using
        End Using

        Dim matchEarliest = DateTime.Today
        Dim matchLatest = matchEarliest.AddDays(8)

        Dim sb As New StringBuilder ' somewhere to save the matching data

        For Each r As DataRow In birthdt.Rows
            Dim dob = Convert.ToDateTime(r.Item("DOB"))

            ' Allow for leap years by transferring the birthday to 1st March - some countries would use 28th February.
            If DateTime.IsLeapYear(dob.Year) AndAlso Not DateTime.IsLeapYear(matchEarliest.Year) AndAlso dob.Month = 2 AndAlso dob.Day = 29 Then
                dob = dob.AddDays(1)
            End If

            Dim nextBirthday = New DateTime(matchEarliest.Year, dob.Month, dob.Day)

            If dob.Month <= matchEarliest.Month AndAlso dob.Day < matchEarliest.Day Then
                ' birthday has already happened this calendar year, make it next year
                nextBirthday = nextBirthday.AddYears(1)
            End If

            If nextBirthday >= matchEarliest AndAlso nextBirthday < matchLatest Then
                ' the record is in the required range
                sb.AppendLine(CStr(r.Item("Name")) & " " & dob.ToString("ddd dd MMMM"))
            End If

        Next

        TextBox1.Text = sb.ToString()

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ShowUpcomingBirthdays()

    End Sub

End Class

如果您不想包括今天。

我创建了一个名为Employee的小类(位于代码底部)。这个答案有点类似于@AndrewMorton。我将Sub分解为几个功能,可以在不破坏其他功能的情况下进行修改以适应

Private Sub DisplayUpcomingBirthdays()
    Dim lstBirthdays As New List(Of Employee)
    Dim dt = RetrieveBirthdays()
    For Each rw As DataRow In dt.Rows
        Dim CurrentYearBirthday As Date = GetCurrentYearBD(CDate(rw.Item("Birthdate")))
        If IsBDThisWeek(CurrentYearBirthday) Then
            lstBirthdays.Add(New Employee(CurrentYearBirthday, rw.Item("Name").ToString))
        End If
    Next
    Dim SortedList = SortByBirthdays(lstBirthdays)
    ListBox1.DataSource = SortedList
End Sub

Private Function RetrieveBirthdays() As DataTable
    Dim query = "Select Name, Birthdate From Employes;"
    Dim birthdt As New DataTable
    Using cn As New SqlConnection("YourConnectionString")
        Using cmd As New SqlCommand(query, cn)
            cn.Open()
            birthdt.Load(cmd.ExecuteReader)
        End Using
    End Using
    Return birthdt
End Function

Private Function GetCurrentYearBD(BirthDate As Date) As Date
    Dim Day As Integer = BirthDate.Day
    Dim Month As Integer = BirthDate.Month
    Dim Year As Integer = Now.Year
    'Bithday is celebrated on the 28th when it is not a leap year
    If Month = 2 AndAlso Day = 29 AndAlso Not DateTime.IsLeapYear(Year) Then
        Day = 28
    End If
    Return New DateTime(Year, Month, Day)
End Function

Private Function IsBDThisWeek(BD As Date) As Boolean
    Dim Tomorow = Now.AddDays(1)
    Dim WeekFromNow = Now.AddDays(7)
    If BD >= Tomorow AndAlso BD <= WeekFromNow Then
        Return True
    End If
    Return False
End Function

Private Function SortByBirthdays(Employees As List(Of Employee)) As List(Of Employee)
    Dim lst = (From emp In Employees
               Order By emp.Birthdate
               Select emp).ToList
    Return lst
End Function

Public Class Employee
    Public Property Birthdate As Date
    Public Property Name As String

    Public Sub New(BD As Date, eName As String)
        Birthdate = BD
        Name = eName
    End Sub

    Public Overrides Function ToString() As String
        Return $"{Name},  {Birthdate.ToString("MMMM dd")}"
    End Function
End Class
Private子显示即将到来的生日()
(员工)的新生日列表
Dim dt=检索生日()
对于每个rw作为dt.行中的数据行
Dim CURRENTYEARBATH As Date=GetCurrentYearBD(CDate(rw.Item(“生日”))
如果是本周(当前年份生日),则
添加(新员工(CurrentYearBirthday,rw.Item(“姓名”).ToString))
如果结束
下一个
Dim SortedList=SortByBirthdays(第一个生日)
ListBox1.DataSource=SortedList
端接头
私有函数RetrieveBirthdays()作为DataTable
Dim query=“从员工中选择姓名、出生日期;”
Dim birthdt作为新数据表
将cn用作新的SqlConnection(“YourConnectionString”)
使用cmd作为新的SqlCommand(query,cn)
cn.Open()
birthdt.Load(命令ExecuteReader)
终端使用
终端使用
返回出生日期
端函数
私有函数GetCurrentYearBD(生日作为日期)作为日期
Dim Day作为整数=生日.Day
整数形式的月份=出生日期。月份
Dim Year As Integer=现在。年份
比特日是在28日庆祝的,那时不是闰年
如果月=2,日=29,且不是DateTime.IsLeapYear(年),则
天=28
如果结束
返回新日期时间(年、月、日)
端函数
私有函数IsBDThisWeek(BD作为日期)为布尔值
Dim Tomorow=Now.AddDays(1)
Dim WeekFromNow=Now.AddDays(7)

如果BD>=Tomorrow并且BD在此处读取有关可解析格式的信息:。此外,考虑使用.NET DATETIME而不是DATE。1)数据库中列的类型是什么?(是varchar、datetime还是其他的?)2)如果出生日期在2月29日,但您计算的年份不是闰年,您希望发生什么情况?该列是datetime,希望检查那些在某一周即将出生的人,因此我代码中的dys2如果该值介于1和7之间,则为itI尝试过,但现在出现此错误年、月和日参数描述了一个不可表示的日期时间。@mcvision您能粘贴您正在使用的确切代码吗?谢谢,我想我已经弄明白了这就是我所做的。我计算了当前年份的年龄,并将结果添加到出生日期的年份部分。
Private Sub DisplayUpcomingBirthdays()
    Dim lstBirthdays As New List(Of Employee)
    Dim dt = RetrieveBirthdays()
    For Each rw As DataRow In dt.Rows
        Dim CurrentYearBirthday As Date = GetCurrentYearBD(CDate(rw.Item("Birthdate")))
        If IsBDThisWeek(CurrentYearBirthday) Then
            lstBirthdays.Add(New Employee(CurrentYearBirthday, rw.Item("Name").ToString))
        End If
    Next
    Dim SortedList = SortByBirthdays(lstBirthdays)
    ListBox1.DataSource = SortedList
End Sub

Private Function RetrieveBirthdays() As DataTable
    Dim query = "Select Name, Birthdate From Employes;"
    Dim birthdt As New DataTable
    Using cn As New SqlConnection("YourConnectionString")
        Using cmd As New SqlCommand(query, cn)
            cn.Open()
            birthdt.Load(cmd.ExecuteReader)
        End Using
    End Using
    Return birthdt
End Function

Private Function GetCurrentYearBD(BirthDate As Date) As Date
    Dim Day As Integer = BirthDate.Day
    Dim Month As Integer = BirthDate.Month
    Dim Year As Integer = Now.Year
    'Bithday is celebrated on the 28th when it is not a leap year
    If Month = 2 AndAlso Day = 29 AndAlso Not DateTime.IsLeapYear(Year) Then
        Day = 28
    End If
    Return New DateTime(Year, Month, Day)
End Function

Private Function IsBDThisWeek(BD As Date) As Boolean
    Dim Tomorow = Now.AddDays(1)
    Dim WeekFromNow = Now.AddDays(7)
    If BD >= Tomorow AndAlso BD <= WeekFromNow Then
        Return True
    End If
    Return False
End Function

Private Function SortByBirthdays(Employees As List(Of Employee)) As List(Of Employee)
    Dim lst = (From emp In Employees
               Order By emp.Birthdate
               Select emp).ToList
    Return lst
End Function

Public Class Employee
    Public Property Birthdate As Date
    Public Property Name As String

    Public Sub New(BD As Date, eName As String)
        Birthdate = BD
        Name = eName
    End Sub

    Public Overrides Function ToString() As String
        Return $"{Name},  {Birthdate.ToString("MMMM dd")}"
    End Function
End Class