Issues with Datediff function

J

James.

Ok, try not to laugh. I have two dates in VBA, I wish to find the years
between them using the datediff function.

date1 = #1/1/2000#
date2 = #1/1/2005#
date3 = DateDiff("yyyy", date2, date1)

When I run this date 3 is :
12/25/1899

I was kinda hoping for 5 years. I have changed the order of the date value
and still get an odd result. Can anyone tell me the silly mistake I am
making here please.

Thanks.

James D.
 
M

Matthias Klaey

James. said:
Ok, try not to laugh. I have two dates in VBA, I wish to find the years
between them using the datediff function.

date1 = #1/1/2000#
date2 = #1/1/2005#
date3 = DateDiff("yyyy", date2, date1)

When I run this date 3 is :
12/25/1899

I was kinda hoping for 5 years. I have changed the order of the date value
and still get an odd result. Can anyone tell me the silly mistake I am
making here please.

Thanks.

James D.

In the immediate window:

? DateDiff("yyyy", #1/1/2000#, #1/1/2005#)
5

The result from DateDiff is a Long, not a date. Assign the result to
an Long variable, not to date3.

HTH
Matthias Kläy
 
M

Marshall Barton

James. said:
Ok, try not to laugh. I have two dates in VBA, I wish to find the years
between them using the datediff function.

date1 = #1/1/2000#
date2 = #1/1/2005#
date3 = DateDiff("yyyy", date2, date1)

When I run this date 3 is :
12/25/1899

I was kinda hoping for 5 years. I have changed the order of the date value
and still get an odd result. Can anyone tell me the silly mistake I am
making here please.


Ha ha ha, I tried not to, but couldn't help myself ;-)

You asked it to calculate the number of years, but then
stuff the result into a date variable. What you're seeing
the the date -5

You should use this instead
Dim intYears As Integer
. . .
intYears = DateDiff("yyyy", date1, date2)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top