Subtracting one date from another

donrecardo

Member
Joined
Sep 24, 2009
Messages
14
Programming Experience
Beginner
Hi ,
I have a form with 3 txtboxes. The user has to enter their
date of birth in the 3 boxes in the form

DD in the first box
MM in the second and
YYYY in the third

I then need to get todays date and take their date of
birth from todays date so that I can output to 3 labels
the length of time they have been alive in years,months
and days

I assume I will need to use timespan? in some way but I am
not sure how , or is there perhaps a better way ?

Regards
Don
 
when you do subtraction between two DateTime objects you get a TimeSpan object.

VB.NET:
Dim myDate1 as DateTime = "01/01/1980"
Dim diff as TimeSpan = Now - myDate1
 
Thank you for replying however I cant get it to run.
I am very much the newbie so I guess I am doing something wrong

I put the code is as you wrote it and the first line was fine but
the second line played up, it didnt like " Now"
I thought rather than ...

Dim diff as Timespan = Now - mydate1 it might have to be
Dim diff as Timespan =DateTime.Now - myDate1

it seemed to accept " Now" ok but came up with the message...

The Operator '-' is not defined for type 'Date'

so I am still stuck

Don

when you do subtraction between two DateTime objects you get a TimeSpan object.

VB.NET:
Dim myDate1 as DateTime = "01/01/1980"
Dim diff as TimeSpan = Now - myDate1
 
You have to use the Subtract method of the Date, the Operator '-' was not defined for type 'Date' in .Net 1.
or upgrade upgrade upgrade :)
 
I did your homework for you. :)

Enjoy. Hope you get an A.
 

Attachments

  • AgeCalculator.zip
    98.1 KB · Views: 37
Last edited by a moderator:
I did your homework for you. :)

Enjoy. Hope you get an A.

Hi gir489
That was really good of you to go to that much trouble for me.
As for getting an 'A' , I think I might have got expelled for cheating , that was quite a way above our standard at the momment :eek:

However I am sorry but I cant get it to run . My month of birth is July so I tried entering 07 thinking that would be the correct format , but on entering the zero it said it was invalid. Not giving up I tried entering just the number 7
but it said that number was too high. In fact on trying it said any number >1 was too high for the month.
I tried Month 1 , day 1, and year 1950 and it ran fine but when I tried month 1, day 13 , year 1950 it crashed out

I tried looking through the code and while some of it made sense to me a lot of it did not . I had never even heard of Datediff before

I cant help but think my tutor expects us to use a much simpler approach than this . We only go to college for 2 hours each week and we are only on week 4 of a 16 week course for absolute beginners .

Week 1 we did an intro to VB .net ( just a general overview)
Week 2 creating a user interface ( Putting buttons and labels on a form, and "hello world ")
Week 3 we did a bit more coding, making shopping lists etc and getting it to add up totals

Week 4 Variables and Constants , ( Declaring and assigning them) these are the 2 projects we did to try to master what we learned about variables, It gives you an idea of the ( low ) standard we are up to Chapter 3 Projects

Next week ( week 5 ) we move on to exciting decision making with If, Else, Case, etc

So really although your answer was very professional and I hope one day I can write code half as good as that I think perhaps she is expecting something a little simpler from us .
Here is the actual task we were set , its the first one on this page and is the Zodiak of fortune program

Chapter 4 Projects

Regards

Don
 
I think you might've downloaded one of the older builds.

Ever since 3:52AM onward, I was updating it until 5:13AM. Fixing crashes and out-of-bounds errors.

http://img193.imageshack.us/img193/1520/1131950.png

DateDiff is a simple function found in VisualBasic since VB5. You feed the function 3 variables.

What you want done.
First date.
Second date.

It does the comparison x done from the second date minus the first date. Giving you an answer in an integer form.

I'll upload a highly documented version, if you'd like.

The only documentation I added was about the pre-month HotFix. That's only so you know why that out-of-place looking code was there.

The main code you need to be looking at is here:

VB.NET:
                    UserDate = txtMonth.Text & "/" & txtDay.Text & "/" & Year
                    txtMonthsOld.Text = DateDiff("m", UserDate, Now.Date)
                    txtDaysOld.Text = DateDiff("d", UserDate, Now.Date)
                    txtYearsOld.Text = DateDiff("yyyy", UserDate, Now.Date)

I create my first comparison variable from the 3 text boxes, creating a MM/DD/YYYY string. Then it sets the Read-Only text boxes to that resulting calculations of the DateDiffs between the entered date and Now.Date.
 
Last edited:
gir489 - you need to start using Option Strict On. I suggest you go back to the project you wrote, turn it on, and see how many problems there are ;)
 
gir489 - you need to start using Option Strict On. I suggest you go back to the project you wrote, turn it on, and see how many problems there are ;)
Here's a build with Option Strict On. No errors.
 

Attachments

  • AgeCalculator.zip
    98.1 KB · Views: 35
Here's a build with Option Strict On. No errors.
In that case you must have uploaded the wrong project, because that code is loaded with implictic conversion errors, in addtion to other errors in code logic ;)
 
No errors arise. If you get them, show me.

I ran into the overloading if > problem in the other months besides February.

Here's one where they all check for blanks before checking if >.
 

Attachments

  • AgeCalculator.zip
    98.1 KB · Views: 29
Last edited:
gir489 said:
No errors arise. If you get them, show me.
You have 15 implicit conversion errors. You will see them with Option Strict turned on. The first one is this:
Year = txtYear.Text
Error 1 Option Strict On disallows implicit conversions from 'String' to 'Integer'.
These will show up as conversion errors as well, but is a common beginner error in code logic, the If statement simply doesn't work like that:
If txtMonth.Text = "1" Or "3" Or "5" Or "7" Or "8" Or "10" Or "12" Then
You figure out how to fix it, I recommend you have a look at the Select Case statement for cases like this.
 
Hi everyone,

I do appreciate the help you are all giving me , and I think its
beginning to make more sense now.
I can see how its converting all the user inputs into one string and then
comparing it with the datediff function.

I will play with what you have given me for a while and see what comes out
of it . I can see that although it looks a real complex piece of code that most
of it is checking for wrong user inputs such as months and days that cant
exist.
While we in college are still beginners we are not yet expected to do all
this error checking and with that taken out the task looks achievable .

Will give you a shout if I still cant get it working but for now I shall go give it a try

Once again

Many thanks to you all

Don
 
Whoops
I spoke too soon

I tried running the program but once again it failed to run . It works fine
if I input my Bday as 1st Jan 2001 but not with 13th July 1949 .

Further more when I put in
1 jan 2001 I got 105 Mths , 3211 Days
2 jan 2001 I got 104 Mths , 3180 days

it should have said 105 Mths , 3210 Days

I managed to figure this one out for myself , the line that converts the
users 3 inputs to a string formatted as ....

MM/DD/YYYY when it should really have formatted them to
DD/MM/YYYY

So that part works ok now and I think I can follow how the calculation works

Further down the program there is code to determine everything input by the user was valid , some I understand and some I dont

Here was some I dont understand , can someone please tell me what it
all means please,
especially,,,,,,

will the action in the code below occur on any key pressed ? or just a particular key ? or maybe even on a mouse click?

also what is e.handled ( true/false) I assume its something to do with error trapping

Lastly what is all this telling me ? ...
If [Char].IsDigit(e.KeyChar) OrElse AscW(e.KeyChar) = CInt(Keys.Back) Or AscW(e.KeyChar) = CInt(Keys.Alt) Or AscW(e.KeyChar) = CInt(Keys.Control)



VB.NET:
    Private Sub txtMonth_OnKeyPress(ByVal Sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtMonth.KeyPress
        If [Char].IsDigit(e.KeyChar) OrElse AscW(e.KeyChar) = CInt(Keys.Back) Or AscW(e.KeyChar) = CInt(Keys.Alt) Or AscW(e.KeyChar) = CInt(Keys.Control) Then
            e.Handled = False
            Return
        End If
        e.Handled = True
    End Sub
    Private Sub txtDay_OnKeyPress(ByVal Sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtDay.KeyPress
        If [Char].IsDigit(e.KeyChar) OrElse AscW(e.KeyChar) = CInt(Keys.Back) Or AscW(e.KeyChar) = CInt(Keys.Alt) Or AscW(e.KeyChar) = CInt(Keys.Control) Then
            e.Handled = False
            Return
        End If
        e.Handled = True
    End Sub
    Private Sub txtYear_OnKeyPress(ByVal Sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtYear.KeyPress
        If [Char].IsDigit(e.KeyChar) OrElse AscW(e.KeyChar) = CInt(Keys.Back) Or AscW(e.KeyChar) = CInt(Keys.Alt) Or AscW(e.KeyChar) = CInt(Keys.Control) Then
            e.Handled = False
            Return
        End If
        If e.KeyChar = Chr(Keys.Enter) Then
            btnCalc.PerformClick()
        End If
        e.Handled = True
    End Sub

Hopefully if some one can answer my questions I might understand a little bit more

Regards
Don
 
Yes the event is triggered with each keypress on the specified controled. E.Handled is telling it whether or not to accept the user key input.

There are many options to choose from in ways of validating your data. For example you could just check all input once, when they click the calculate button. And there are other controls such as the NumericUpDown control that could be used to ensure only a numeric value was input.
 
Back
Top