Link to home
Start Free TrialLog in
Avatar of RIAS
RIASFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Subtract dates in vb.net

Hello,
How do I subtract two dates and check whether it is 1 year or less than 1 year.

Cheers
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RIAS

ASKER

ThanksAndy, Will try and get back
You can try this code, this was in c# change accordingly to VB
DateTime bday = new DateTime(1984, 03, 26);
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (bday > now.AddYears(-age)) age--;
MessageBox.Show(age.ToString());

Open in new window

Avatar of RIAS

ASKER

Thanks Andy, it worked!
Thanks Dorababu for the efforts!
not sure about vb but what i'd do is convert the two dates to ticks; find the difference between the two create a new datetime with the difference in ticks as the constructor parameter, then check if the year is greater than 1
using System;

namespace pc.datediff
{
    class Program
    {
        static void Main(string[] args)
        {
            var d1 = DateTime.Now.Ticks;
            var d2 = DateTime.Now.AddYears(-1).AddSeconds(-1).Ticks;

            var result = d1 - d2;
            Console.WriteLine(new DateTime(result).Year);

        }
    }
}

Open in new window


sorry that the code is in c# but it's more or less the same idea
@Pawel, the question is vb.net not vb and .net has the timespan class for handling differences between datetimes.  No need to reinvent the wheel.