[AccessD] Create a random date/time

Gustav Brock gustav at cactus.dk
Mon Aug 31 10:42:40 CDT 2015


Hi all

Forgot one thing:  To shuffle the start position of the sequence of Rnd by calling Randomize.

If missing, the function would generate the same sequence of dates whenever the application was relaunched. It is included now:

<code>
Public Function DateRandom( _
    Optional ByVal UpperDate As Date = #12/31/9999#, _
    Optional ByVal LowerDate As Date = #1/1/100#, _
    Optional ByVal DatePart As Boolean = True, _
    Optional ByVal TimePart As Boolean = True, _
    Optional ByVal MilliSecondPart As Boolean = False) _
    As Date
    
'   Generates a random date/time - optionally within the range of LowerDate and/or UpperDate.
'   Optionally, return value can be set to include date and/or time and/or milliseconds.
'
'   2015-08-28. Gustav Brock, Cactus Data ApS, CPH.
'   2015-08-29. Modified for uniform distribution as suggested by Stuart McLachlan by
'               combining a random date and a random time.
'   2015-08-30. Modified to return selectable and rounded value parts for
'               Date, Time, and Milliseconds.
'   2015-08-31. An initial  call of Randomize it included to prevent identical sequences.
    
    Const SecondsPerDay As Long = 60& * 60& * 24&
    
    Dim DateValue   As Date
    Dim TimeValue   As Date
    Dim MSecValue   As Date
    
    ' Shuffle the start position of the sequence of Rnd.
    Randomize

    ' If all parts are deselected, select date and time.
    If Not DatePart And Not TimePart And Not MilliSecondPart = True Then
        DatePart = True
        TimePart = True
    End If
    If DatePart = True Then
        ' Remove time parts from UpperDate and LowerDate as well from the result value.
        ' Add 1 to include LowerDate as a possible return value.
        DateValue = CDate(Int((Int(UpperDate) - Int(LowerDate) + 1) * Rnd) + Int(LowerDate))
    End If
    If TimePart = True Then
        ' Calculate a time value rounded to the second.
        TimeValue = CDate(Int(SecondsPerDay * Rnd) / SecondsPerDay)
    End If
    If MilliSecondPart = True Then
        ' Calculate a millisecond value rounded to the millisecond.
        MSecValue = CDate(Int(1000 * Rnd) / 1000 / SecondsPerDay)
    End If
    
    DateRandom = DateValue + TimeValue + MSecValue

End Function
</code>

/gustav 



More information about the AccessD mailing list