Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


Calculate the difference between two date/time fields in MS Access

Posted on 2011-03-14
Medium Priority
Last Modified: 2012-08-13
I am having some difficulty calculating the difference between two date/time fields in a form.  The issue i have is calculating the difference using the "DateDiff" function, excluding weekends and only counting hours worked between 8:00 AM - 6:00 PM.  A holiday table is an option but not a necessity.  Appreciate your assistance.
Question by:kev_hinds
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 48

Expert Comment

by:Dale Fye
ID: 35130286
What information are you trying to display in the form (something like 8.5 hours)?

Part of your challenge will be dealing with your 8:00 AM to 6:00 PM issue.  Assuming you have fields [Time In] and [Time Out] and you want to compute the difference between these values, but only within the bounds of the 8AM-6PM, you will first need to identify which date/time values to use.  I do this with a couple of general purpose functions (below) named fnMin() and fnMax().  These functions return the minimum and maximum values from among an array of parameters passed to them.  So the way I would do this is something like:

lngDurationMin = DateDiff("n", fnMax([Time In], #08:00#), fnMin(#18:00#, [Time Out]))

You can then convert the minutes to hours and minutes to display that information any way you want.

Public Function fnMin(ParamArray ValList() As Variant) As Variant

   Dim intLoop As Integer
   Dim myVal As Variant
   For intLoop = LBound(ValList) To UBound(ValList)
      If Not IsNull(ValList(intLoop)) Then
         If IsEmpty(myVal) Then
            myVal = ValList(intLoop)
         ElseIf ValList(intLoop) < myVal Then
            myVal = ValList(intLoop)
         End If
      End If
   fnMin = myVal
End Function
Public Function fnMax(ParamArray ValList() As Variant) As Variant

   Dim intLoop As Integer
   Dim myVal As Variant
   For intLoop = LBound(ValList) To UBound(ValList)
      If Not IsNull(ValList(intLoop)) Then
         If IsEmpty(myVal) Then
            myVal = ValList(intLoop)
         ElseIf ValList(intLoop) > myVal Then
            myVal = ValList(intLoop)
         End If
      End If
   fnMax = myVal
End Function

Open in new window


Expert Comment

ID: 35130294

if you want second format, you may try this
DateDiff('s',[date1],[date2]) AS Expr1

Open in new window

LVL 93

Accepted Solution

Patrick Matthews earned 1000 total points
ID: 35130465

You may want to see the function I posted to this previous question:


It allows you to specify what the "normal business hours" are, what weekdays are considered "business days", and also allows you to have a holidays table to do a holiday override.

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 48

Expert Comment

by:Dale Fye
ID: 35130505

You are such an overachiever.   ;-)


Author Comment

ID: 35130512
@ fved - I inserted your modules in my afterupdate function for the date returned however it gives me a large negative number - I changed the "n" to a "h" as i need my output in hours - preferably in whole numbers however the number is still negative

the format is as follows:
date received: 2/18/2010 9:01:00 AM
date returned: 2/19/2010 11:35:00 AM

Expected result: 13 hours

Author Comment

ID: 35130616
@matthewspatrick: Thanks! Works perfectly!!! Appreciated.
LVL 52

Expert Comment

by:Gustav Brock
ID: 35130636
You can use the function below.
To obtain a rounded count of hours, use:

intHours = Val(Format(ISO_WorkTimeDiff(#2/18/2010 9:01:00 AM#, #2/19/2010 11:35:00 AM#, False) / 60, "0"))


Public Function ISO_WorkTimeDiff( _
  ByVal datDateTimeFrom As Date, _
  ByVal datDateTimeTo As Date, _
  Optional ByVal booNoHours As Boolean) _
  As Long

' Purpose: Calculate number of working minutes between date/times datDateTimeFrom and datDateTimeTo.
' Assumes: 5 or 6 working days per week. Weekend is (Saturday and) Sunday.
' Returns: "Working minutes". Divide by 60 to obtain working hours.
' Limitation: Does not count for public holidays.
' May be freely used and distributed.
' 2001-06-26. Gustav Brock, Cactus Data ApS, Copenhagen
' If booNoHours is True, time values are ignored.

  ' Specify begin and end time of daily working hours.
  Const cdatWorkTimeStart   As Date = #8:00:00 AM#
  Const cdatWorkTimeStop    As Date = #6:00:00 PM#
  Const cbytWorkdaysOfWeek  As Byte = 5

  Dim bytSunday             As Byte
  Dim intWeekdayDateFrom    As Integer
  Dim intWeekdayDateTo      As Integer
  Dim datTimeFrom           As Date
  Dim datTimeTo             As Date
  Dim lngDays               As Long
  Dim lngMinutes            As Long
  Dim lngWorkMinutesDaily   As Long
  ' No special error handling.
  On Error Resume Next
  If DateDiff("n", datDateTimeFrom, datDateTimeTo) <= 0 Then
    ' Nothing to do. Return zero.
    ' Calculate number of daily "working minutes".
    lngWorkMinutesDaily = DateDiff("n", cdatWorkTimeStart, cdatWorkTimeStop)
    ' Find ISO weekday for Sunday.
    bytSunday = WeekDay(vbSunday, vbMonday)
    ' Find weekdays for the dates.
    intWeekdayDateFrom = WeekDay(datDateTimeFrom, vbMonday)
    intWeekdayDateTo = WeekDay(datDateTimeTo, vbMonday)
    ' Compensate weekdays' value for non-working days (weekends).
    intWeekdayDateFrom = intWeekdayDateFrom + (intWeekdayDateFrom = bytSunday)
    intWeekdayDateTo = intWeekdayDateTo + (intWeekdayDateTo = bytSunday)
    ' Calculate number of working days between the weeks of the two dates.
    lngDays = (cbytWorkdaysOfWeek * DateDiff("w", datDateTimeFrom, datDateTimeTo, vbMonday, vbFirstFourDays))
    ' Add number of working days between the two weekdays, ignoring number of weeks.
    lngDays = lngDays + intWeekdayDateTo - intWeekdayDateFrom - (cbytWorkdaysOfWeek * (intWeekdayDateTo < intWeekdayDateFrom))
    If Not booNoHours = True Then
      ' Extract begin and stop hour (time) for the working period.
      datTimeFrom = TimeSerial(Hour(datDateTimeFrom), Minute(datDateTimeFrom), Second(datDateTimeFrom))
      datTimeTo = TimeSerial(Hour(datDateTimeTo), Minute(datDateTimeTo), Second(datDateTimeTo))
      ' Adjust times before or after daily working hours to boundaries of working hours.
      If DateDiff("n", datTimeFrom, cdatWorkTimeStart) > 0 Then
        datTimeFrom = cdatWorkTimeStart
      ElseIf DateDiff("n", datTimeFrom, cdatWorkTimeStop) < 0 Then
        datTimeFrom = cdatWorkTimeStop
      End If
      If DateDiff("n", datTimeTo, cdatWorkTimeStart) > 0 Then
        datTimeTo = cdatWorkTimeStart
      ElseIf DateDiff("n", datTimeTo, cdatWorkTimeStop) < 0 Then
        datTimeTo = cdatWorkTimeStop
      End If
      ' Calculate number of working minutes between the two days, ignoring number of days.
      lngMinutes = DateDiff("n", datTimeFrom, datTimeTo)
    End If
    ' Calculate number of working minutes between the two days using the workday count.
    lngMinutes = lngMinutes + (lngDays * lngWorkMinutesDaily)
  End If
  ISO_WorkTimeDiff = lngMinutes

End Function

Open in new window

LVL 48

Expert Comment

by:Dale Fye
ID: 35130648

You didn't mention that these values might span multiple days, bad assumption on my part.

Author Comment

ID: 35130775
No problem fved ... i will try to be more succinct next time ... was my first question ... appreciate the prompt feedback though.  thanks.
LVL 18

Expert Comment

ID: 35130794
I would create a specific calendar table, with not only days, but hours.

Here is the SQL to create a calendar table with hours
DECLARE  @integers  TABLE (i integer)
insert into @integers (i) values (0)
insert into @integers (i) values (1)
insert into @integers (i) values (2)
insert into @integers (i) values (3)
insert into @integers (i) values (4)
insert into @integers (i) values (5)
insert into @integers (i) values (6)
insert into @integers (i) values (7)
insert into @integers (i) values (8)
insert into @integers (i) values (9)  

create table calendar
( date          datetime   not null primary key,
HourOfDay int,
DayofWeek int

declare @startdate datetime
set @startdate = '2011-01-01'
  into calendar
select dateadd(hour,n,@startdate)
     , DATEPART(hour,dateadd(hour,n,@startdate))
     , DATEPART(WEEKDAY,dateadd(hour,n,@startdate))
  from (
       select g.i*100000+m.i*10000+k.i*1000+h.i*100+t.i*10+u.i  as n
         from @integers u
            , @integers t
            , @integers h
            , @integers k
            , @integers m
            , @integers g
       ) as numbers
 where n between 0 and 100000
    by n

Then you can query the table to get the number of hours between two times:
SELECT COUNT(*) FROM Calendar WHERE date between '2011-01-03 5:00' AND '2011-01-11 9:00' AND hourofday between 9 and 18 and dayofweek between 2 and 6

Then just add the minutes to and from the hour boundary.

LVL 48

Expert Comment

by:Dale Fye
ID: 35130816
In that case, welcome to EE.  

It helps to be as specific as possible (without getting too long), to include sample data, so that the experts can actually try their solution with a couple of examples of your data.

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In earlier versions of Windows (XP and before), you could drag a database to the taskbar, where it would appear as a taskbar icon to open that database.  This article shows how to recreate this functionality in Windows 7 through 10.
This article describes two methods for creating a combo box that can be used to add new items to the row source -- one for simple lookup tables, and one for a more complex row source where the new item needs data for several fields.
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

604 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question