I got really bored today that i decided to create a demo application. There's nothing cheesy about this one since it is a simple implementation of the DateDiff function in calculating the difference of two Date values in years. I was thinking of writing something more interesting than this one but I didn't have the time to create a real braintwisting app. Anyway, enough with the crappy introduction. Here's the methods written in both C# and VB.NET:
[C# Sample]
public long CalculateAge(System.DateTime startDate)
{
return CalCulateAge(startDate, DateTime.Today);
}
public long CalculateAge(System.DateTime startDate, System.DateTime endDate)
{
long age = 0;
try
{
if (Month(startDate) == Month(endDate))
{
age = DateDiff(DateInterval.Year, startDate, endDate);
}
else if (Month(startDate) == Month(endDate))
{
if (Day(startDate) == Day(endDate))
{
age = DateDiff(DateInterval.Year, startDate, endDate);
}
else if (Day(startDate) == Day(endDate))
{
age = DateDiff(DateInterval.Year, startDate, endDate);
}
else if (Day(startDate) == Day(endDate))
{
age = DateDiff(DateInterval.Year, startDate, endDate) - 1;
}
}
else if (Month(startDate) == Month(endDate))
{
age = DateDiff(DateInterval.Year, startDate, endDate) - 1;
}
else
{
age = 0;
}
}
catch (System.Exception ex)
{
throw ex;
}
return age;
}
[VB.NET Sample]
Public Function CalculateAge(ByVal startDate As System.DateTime) As Long
Return CalculateAge(startDate, DateTime.Today)
End Function
Public Function CalculateAge(ByVal startDate As System.DateTime, ByVal endDate As System.DateTime) As Long
Dim age As Long = 0
Try
Select Case Month(startDate)
Case Is < Month(endDate)
age = DateDiff(DateInterval.Year, startDate, endDate)
Case Is = Month(endDate)
Select Case Day(startDate)
Case Is < Day(endDate)
age = DateDiff(DateInterval.Year, startDate, endDate)
Case Is = Day(endDate)
age = DateDiff(DateInterval.Year, startDate, endDate)
Case Is > Day(endDate)
age = DateDiff(DateInterval.Year, startDate, endDate) - 1
End Select
Case Is > Month(endDate)
age = DateDiff(DateInterval.Year, startDate, endDate) - 1
Case Else
age = 0
End Select
Catch ex As System.Exception
Throw ex
End Try
Return age
End Function
Geeh, this is boring... :)
Posted
12-14-2005 1:23 AM
by
keithrull