View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.newusers
[email protected] mgeels@gmail.com is offline
external usenet poster
 
Posts: 1
Default Formula needed to calculate difference between Two dates andtimes

Hi,

Here's a function I wrote which displays the time in W days, X hours,
Y minutes and Z seconds. You simply need to set the start date+time,
and the end date + time.

Mark.




Public Function TimeDif(StartTime As Date, EndTime As Date) As String

'################################################# ######################
'################################################# ######################
'####
'#### This function returns a string expression of the number of
'#### days, hours, minutes, and seconds between two dates.
'####
'#### Code written by Mark Geels 10/09/2008
'#### Please retain this
heading
'################################################# ######################
'################################################# ######################


'Define constants
Const HPD = 24, MPD = 1440, SPD = 86400 'hours / minutes /
seconds per day
Const HPC = (1 / HPD), MPC = (1 / MPD), SP = (1 / SPD) 'one
unit (Hour Min Sec) as a percentage of one day

'Define variables
Dim Days, Hours, Minutes, Seconds As Integer
Dim dblTimeDif As Double
Dim strDays, strHours, strMinutes, strSeconds As String


dblTimeDif = EndTime - StartTime


'Set Days
Days = Int(dblTimeDif)
dblTimeDif = dblTimeDif - Days
If Days = 0 Then
strDays = ""
Days = ""
Else: strDays = " Days, "
End If

'Set Hours
Hours = Int(dblTimeDif * HPD)
dblTimeDif = dblTimeDif - (Hours * HPC)
If Days = "" And Hours = 0 Then
strHours = ""
Hours = ""
Else: strHours = " Hours, "
End If

'Set Minutes
Minutes = Int(dblTimeDif * MPD)
dblTimeDif = dblTimeDif - (Minutes * MPC)
If Days = "" And Hours = "" And Minutes = 0 Then
strMinutes = ""
Minutes = ""
Else: strMinutes = " Minutes, and "
End If

'Set Seconds
Seconds = Round(dblTimeDif * SPD, 0)
If Days = "" And Hours = "" And Minutes = "" And Seconds = 0
Then
strSeconds = ""
Seconds = ""
Else: strSeconds = " Seconds"
End If

TimeDif = Days & strDays & Hours & strHours & Minutes & strMinutes
& Seconds & strSeconds


End Function