开发者

VBA: DateDiff Hour Rounded off

开发者 https://www.devze.com 2023-03-04 12:02 出处:网络
I have the following sub in Access 2003 to return the hours elapsed bewteen two datetime fields. Function DateDifferenceHour(dateStart As Date, dateEnd As Date) As String

I have the following sub in Access 2003 to return the hours elapsed bewteen two datetime fields.

Function DateDifferenceHour(dateStart As Date, dateEnd As Date) As String
'Outputs Hours from two dates

Dim age_hour As Double

age_hour = DateDiff("h", dateStart, dateEnd)

DateDifferenceHour = age_hour

End Function

If I have the following: DateDifferenceHour("07/23/2005","07/23/2005 7:30:00开发者_开发知识库 PM").

It correctly returns 19 hours, but in reality, the time elapsed is 19 hours and 30 minutes.

How can I modify it so it can round off to 20 hours?


Edit: My original suggestion was "Compute the difference in minutes, divide by 60, and round the quotient to zero decimal places". However, @Jean-François Corbett showed me the limitation of that approach.

? DateDifferenceHour("07/23/2005 7:00:59 PM","07/23/2005 7:30:00 PM")
1

IOW my first attempt rounded a duration of 29 minutes and 1 second up to 1 hour, which is no good. So instead I suggest using the difference in seconds and dividing by 3600.

Function DateDifferenceHour2(dateStart As Date, dateEnd As Date) As String
    'Outputs Hours from two dates
    DateDifferenceHour2 = _
        Format(DateDiff("s", dateStart, dateEnd) / 3600, "0")
End Function

? DateDifferenceHour2("07/23/2005 7:00:59 PM","07/23/2005 7:30:00 PM")
0

There is still the issue of which rounding approach you want.

I chose Format() thinking you would want 2.5 hours rounded up to 3.

The VBA Round() function uses round-to-even, so Round(2.5, 0) would give you 2.

We don't know which you want; you can tell us. Also, dateStart and dateEnd imply dateStart will not be greater than dateEnd. However, if it can be, consider how you want a negative duration "rounded" to the nearest hour. Here are some examples copied from the Immediate Window.

? Round(-2.5, 0)
-2 
? Round(-1.5, 0)
-2 
? Format(-2.5, "0")
-3
? Format(-1.5, "0")
-2


This works, without any unexpected rounding (aside from the precision of the Date type itself).

Function DateDifferenceHour(dateStart As Date, dateEnd As Date) As String

    ' Rounds .5's to nearest even integer.
    'DateDifferenceHour = CStr( Round( _
    '    CDbl(dateEnd - dateStart) * 24 ) )

    ' Rounds .5's up. 
    DateDifferenceHour = Format( _
        CDbl(dateEnd - dateStart) * 24, "0" )

End Function

I put two rounding options so that it rounds to whole numbers; pick your favourite. It's way better programming practice to round explicitly and transparently than having DateDiff implicitly apply its unusual rounding.

0

精彩评论

暂无评论...
验证码 换一张
取 消