Date Calculations in C#

  • Thread starter Thread starter G
  • Start date Start date
G

G

Hello,

I have two text fields, DateOfBirth and TodaysDate

DateOfBirth:
16/01/1980

TodaysDate:
04/06/2007

I would like to validate using a CompareValidator if possible, that the user
is at LEAST 18 years of age. Does anyone know a quick way to do this
calculation in code behind (no need for a seperate class), which takes
things like previous leap years etc into account?

Quite new to .NET and C# - I am guessing there are some pretty powerful date
functions built in which could do this...

Gary.
 
[...]
I would like to validate using a CompareValidator if possible, that the
user is at LEAST 18 years of age. Does anyone know a quick way to do
this calculation in code behind (no need for a seperate class), which
takes things like previous leap years etc into account?

This should work:

bool IsEighteen(DateTime dob)
{
return dob <= DateTime.Now.AddYears(-18);
}

Replace DateTime.Now with an explicit DateTime value if you want something
other than comparing to "right now" (for example, you suspect that the
computer's clock could be compromised).

How you'd integrate that into a CompareValidator I can't say offhand, not
being familiar with that (yet :) ), but it should be simple once you see
the above.

Pete
 
G said:
Hello,

I have two text fields, DateOfBirth and TodaysDate

DateOfBirth:
16/01/1980

TodaysDate:
04/06/2007

I would like to validate using a CompareValidator if possible, that the
user is at LEAST 18 years of age.

You could try this:
DateOfBirth <= TodaysDate.AddYears(-18)

HTH
Christof
 
* G wrote, On 4-6-2007 18:49:
Hello,

I have two text fields, DateOfBirth and TodaysDate

DateOfBirth:
16/01/1980

TodaysDate:
04/06/2007

I would like to validate using a CompareValidator if possible, that the
user is at LEAST 18 years of age. Does anyone know a quick way to do
this calculation in code behind (no need for a seperate class), which
takes things like previous leap years etc into account?

Quite new to .NET and C# - I am guessing there are some pretty powerful
date functions built in which could do this...

Gary.

If you also need client side validation, you might want to take a look
at Peter's Date Package. It has a large number of date related content.

http://www.peterblum.com

I've used his products for quite some time now, and they beat the
competition hands down.

Jesse
 
Back
Top