计算某人生日下一周年的最快/最简洁的方法是什么?
例如,如果我知道一个人出生于1990年1月31日,而今天是2000年2月10日,那么他们的下一个结婚纪念日将是2001年1月31日。
2月29日应该转到3月1日(例如,如果他们出生于1990年2月29日,他们的一岁生日将是1991年3月1日)。
编辑:哇--我以为这会更琐碎。我真的以为会有一些图书馆的功能我可以用。总之,多亏了你们所有人,我找到了我认为可行的解决方案,解决了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发布于 2008-12-02 14:48:06
我没有在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;
}发布于 2008-12-02 14:57:28
试试这个:
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日,取决于明年是否是闰年.
发布于 2008-12-02 15:12:24
编辑:更改了我的示例,以便它处理跳跃日的生日。
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现在应该可以正常工作了。
https://stackoverflow.com/questions/334149
复制相似问题