Datetime problem

Hi,
How to correct errors

Cannot implicitly convert type 'System.TimeSpan' to 'int'
Operator '<' cannot be applied to operands of type 'System.DateTime' and 'int'

Open in new window

to these 2 lines

                DateTime dt0 = DateTime.Today;int age=birth_dt-dt0;
                if (dt0<18)

Open in new window

LVL 11
HuaMin ChenSystem AnalystAsked:
Who is Participating?
 
Nitin SontakkeDeveloperCommented:
Some minor mistake, I guess. May be you want to say

if(age < 18)

Open in new window


Also you havn't mentioned what birth_dt is. Even I am not sure if direct substraction of dates will give you years. Are you sure?

The best approach would be:

int age = dt0.year - birth_dt.year;

Open in new window

0
 
Nitin SontakkeDeveloperCommented:
Apparently, subtracting two dates will give you TimeSpan object. You cannot use dates as integers. Dates maths is a completely separate thing.
0
 
David Johnson, CD, MVPOwnerCommented:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ee_29075070
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime BirthDay, Today, Years;
            String Not = " Not ";
            BirthDay = Convert.ToDateTime("01/01/1912");
            Today = DateTime.Now;
            Years = BirthDay.AddYears(18);
            if (Today >= Years)
                {
                Not = "";
                }
            Console.WriteLine("User is " + Not + "18 Years Old");
            Console.ReadLine();
        }
    }
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.