Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting the difference between two dates in VB6

Status
Not open for further replies.

afryer

Programmer
Mar 9, 2004
207
GB
Hi All,

I am working on an application, which uses a timer consisting of the year, month, day, hour, minute and second fields. I need to be able to find the exact difference between the two dates (one of the dates is based on the current system date and the other is inputted by the user, but will always be in the past).

I have tried using the DateDiff function, but when it comes to the seconds it displays the total number of seconds, i.e. once it gets past 60 it just continues. I have also tried simply subtracting the dates, i.e.

Code:
l_date_diff = format (l_current_date - l_end_date, "DD/MM/YYYY HH:MM:SS")

This works fine for the hours, minutes and seconds, but the year comes up as 1899 and the month and day as various other random values.

Does anyone have any idea how I can do this without converting all of the values manually. I would expect to get something like the following:

Date1 = 20/08/2006 13:00:00
Date2 = 21/08/2006 14:05:45
Difference (Date2-Date1) = 0y 0m 1d 1h 5m 45s

Any help would be appreciated.

Andrew
 
Just subtract and do the maths. Dates are stored as the number of days since December 31 1899, with fractional days for the time. Start from:
Code:
a= now()
b= #10/19/2005 4:45:23 PM# 
c=abs(a-b)
dd=(int(c))
hh=(24*(c-dd))
mm=60*((hh) - int(hh))
msgbox dd & "days " & int(hh) & "hours " & int(mm) & "mins"
and work your own from there

________________________________________________________________
If you want to get the best response to a question, please check out FAQ222-2244 first.
'If we're supposed to work in Hex, why have we only got A fingers?'
Drive a Steam Roller
 
I would do it like this.
___
[tt]
Private Sub Form_Load()
MsgBox DateDiffEx(#1/1/2000#, Now)
Unload Me
End Sub

Function DateDiffEx(Date1 As Date, Date2 As Date) As String
Dim X As Long, Interval As Variant
For Each Interval In Split("yyyy m d h n s")
X = 0
While DateAdd(Interval, X, Date1) < Date2
X = X + 1
Wend
DateDiffEx = DateDiffEx & X - 1 & Interval & " "
Date1 = DateAdd(Interval, X - 1, Date1)
Next
DateDiffEx = RTrim$(DateDiffEx)
DateDiffEx = Replace$(DateDiffEx, "yyyy", "y")
DateDiffEx = Replace$(DateDiffEx, "n", "m")
End Function[/tt]
 
I would suggest a small change in function declaration.
[tt]
Function DateDiffEx(ByVal Date1 As Date, ByVal Date2 As Date) As String
[/tt]
Passing the arguments by value will ensure variables in the calling function are not modified by the code inside the function.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top