计算今天之后的下一个周年日

时间:2008-12-02 14:42:47

标签: .net vb.net

计算某人生日的下一个周年纪念日最快/最好的方法是什么。

例如,如果我知道一个人出生于1990年1月31日,今天是2000年2月10日,他们的下一个周年纪念日将是2001年1月31日。

2月29日应该到3月1日(例如,如果他们出生于1990年2月29日,他们的第一个生日将是1991年3月1日)。

编辑:哇 - 我认为这会更加微不足道。我真的假设有一些我可以使用的库函数。 Anyhoo,感谢你们所有人,我得到了我认为是一个有效的解决方案,它处理了所有愚蠢的2月29日问题。但它不是很漂亮: - (

Function NextBirthDay2(ByVal dStartDate As Date, ByVal dNow As Date) As Date
    Dim oDate As Date
    Dim bFeb29thHack As Boolean = dStartDate.Month = 2 And dStartDate.Day = 29

    If bFeb29thHack Then
        oDate = New Date(dNow.Year, 3, 1)
    Else
        oDate = New Date(dNow.Year, dStartDate.Month, dStartDate.Day)
    End If

    If (oDate <= dNow) Then
        oDate = oDate.AddYears(1)
    End If

    If Date.IsLeapYear(oDate.Year) And bFeb29thHack Then
        oDate = oDate.AddDays(-1)
    End If
    Return oDate

End Function

4 个答案:

答案 0 :(得分:4)

我没有在VB.Net工作,但我认为C#代码会有足够的意义:

private DateTime nextDate(DateTime currentDate, DateTime anniversaryDate)
{
    DateTime nextDate;
    try{
        nextDate = new DateTime(currentDate.Year, anniversaryDate.Month, anniversaryDate.Day);
    } catch (ArgumentOutOfRangeException)
    {
        //for 29 Feb case.
        nextDate = new DateTime(currentDate.Year, anniversaryDate.Month, anniversaryDate.Day-1).AddDays(1);
    }

    if (nextDate <= currentDate)
        nextDate = nextDate.AddYears(1);
    return nextDate;
}

答案 1 :(得分:2)

试试这个:

int bMon      = 3; // for March
int bDayOfMon = 26 // for March 26th

DateTime nextBirthDay = 
       (new DateTime(DateTime.Today.Year, bMon, bDayOfMon - 1 ))
        .AddDays(1).AddYears((DateTime.Today.Month > bMon || 
          (DateTime.Today.Month == bMon && 
           DateTime.Today.Day > bDayOfMon ))? 1: 0);

如果你的出生日期是2月29日,这将在2月29日或3月1日给你,这取决于明年是否是闰年......

答案 2 :(得分:0)

编辑:更改了我的示例,以便它在leapday处理生日。

Function NextBirthDay(ByVal BirthDate As Date) As Date

    If Not Date.IsLeapYear(Now.Year) And BirthDate.Month = 2 And BirthDate.Day = 29 Then BirthDate.AddDays(1)

    Dim TestDate As Date = New Date(Now.Year, BirthDate.Month, BirthDate.Day)

    If DateDiff(DateInterval.Day, TestDate, Now) > 0 Then

        TestDate.AddYears(1)
        REM now check if NEXT year are leapyear, if so and birthday was a leapday, change back to leapday
        If Date.IsLeapYear(TestDate.Year) AndAlso BirthDate.Month = 2 AndAlso BirthDate.Day = 29 Then
            Return New Date(TestDate.Year, 2, 29)
        Else
            Return TestDate
        End If

    Else

        Return TestDate

    End If

End Function

现在应该按预期工作。

答案 3 :(得分:0)

是否必须是.NET代码?在SQL中实现此功能的最简单方法是使用辅助日历表。谷歌中有很多关于它的参考资料,例如here