Re: Calculating a time and date (counting down)
- From: "Larry Serflaten" <serflaten@xxxxxxxxxxxxxx>
- Date: Sun, 20 Jan 2008 01:05:02 -0600
"Bobzter100" <Bobzter100@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote
Many thnaks to you guys for providing the solution to my VB issue. In the
end, i used Rick's (mainly because it was the most straightforward to
undertake).
Here is another way to skin that cat. Instead of taking the number of seconds,
it takes the interval as a data value. A bit simpler to call if you have the start
and stop times in Date variables. Plus, it allows the user to specify the units
desired in the output...
Ex: Debug.Print FormatUnits(EndTime - StartTime, "HNS", StartTime)
= 123 Hours 10 Minutes 4 Seconds
LFS
Function FormatUnits(ByVal Period As Date, Pattern As String, Optional Start As Date) As String
' <period> - the length of time to format.
' <pattern> - the units to include. the largest unit will include all larger,
' the smallest unit will truncate all smaller. Output is always
' largest to smallest of all included units. (see DateAdd for unit ID)
' <start> - the beginning date of the <period> value. (accounts for differing
' - unit sizes, eg; days in a month, leap year, etc.) Default = Now
' RETURNS - Formated string containing requested units. (Absolute values)
Dim out As String
Dim halt As Date
Dim idx As Long, pat As Long, cnt As Long
Dim unit, name, id
' init variables
name = VBA.Array("Years", "Quarters", "Months", "Weeks", "Days", "Hours", "Minutes", "Seconds")
id = VBA.Array("yyyy", "q", "m", "ww", "d", "h", "n", "s")
halt = Start + Abs(Period) ' DateAdd("s", 1, Start + Abs(Period))
If IsMissing(Start) Then
Start = Now
End If
' Extract pattern
For Each unit In id
If InStr(1, Pattern, Left$(unit, 1), vbTextCompare) Then
pat = pat Or (2 ^ idx)
End If
idx = idx + 1
Next
' Build output
For idx = 0 To 7
If pat And (2 ^ idx) Then
' Include unit
unit = id(idx)
cnt = DateDiff(unit, Start, halt)
If DateAdd(unit, cnt, Start) > halt Then
cnt = cnt - 1
End If
Start = DateAdd(unit, cnt, Start)
out = out & Str(cnt) & " " & name(idx)
' Handle trailing 's' (plurals)
If cnt = 1 Then
out = Left$(out, Len(out) - 1)
End If
End If
Next
FormatUnits = out
End Function
.
- Follow-Ups:
- Re: Calculating a time and date (counting down)
- From: Larry Serflaten
- Re: Calculating a time and date (counting down)
- References:
- RE: Calculating a time and date (counting down)
- From: Bobzter100
- RE: Calculating a time and date (counting down)
- Prev by Date: Re: VB6 SendMessage and WM_COPYDATA
- Next by Date: Re: How's dot.net doing nowadays?
- Previous by thread: RE: Calculating a time and date (counting down)
- Next by thread: Re: Calculating a time and date (counting down)
- Index(es):
Relevant Pages
|