I'm new to vb scripts please help me.
I'm generating Random year by appending last two digits randomly as shown bellow but i want to generate random date DDMMYYYY format between start date and end date provided by user.
Randomize
tmp = Int((92 - 70 + 1) * Rnd + 70)
tmp1= "01/05/19" & tmp
Use this as a starting point
Option Explicit
Function getRandomDate( startDate, endDate )
getRandomDate = DateAdd( _
"d" _
, Fix( DateDiff("d", startDate, endDate ) * Rnd ) _
, startDate _
)
End Function
Dim startDate, endDate
startDate = CDate("2016/03/10")
endDate = CDate("2017/09/30")
Randomize
Dim i
For i = 0 To 100
WScript.Echo getRandomDate( startDate, endDate )
Next
It just calculates the number of days between the start and end dates and selects a random in this range of days to add to the start date.
As an addendum to @mc-nd 's answer
When using Rnd()
to generate random numbers you sure to use Randomize
to initialise the Random Number Generator using the System Time as a seed value or this happens.
Option Explicit
Function getRandomDate( startDate, endDate )
getRandomDate = DateAdd( _
"d" _
, Fix( DateDiff("d", startDate, endDate ) * Rnd ) _
, startDate _
)
End Function
Dim startDate, endDate
startDate = CDate("2016/03/10")
endDate = CDate("2017/09/30")
Dim i
For i = 0 To 10
WScript.Echo getRandomDate( startDate, endDate )
Next
1st Output:
15/04/2017
07/01/2017
02/02/2017
21/08/2016
28/08/2016
24/05/2017
17/03/2016
16/05/2017
16/06/2017
17/04/2017
04/04/2016
2nd Output:
15/04/2017
07/01/2017
02/02/2017
21/08/2016
28/08/2016
24/05/2017
17/03/2016
16/05/2017
16/06/2017
17/04/2017
04/04/2016
Add the Randomize
statement to the code to see the difference;
Option Explicit
Function getRandomDate( startDate, endDate )
getRandomDate = DateAdd( _
"d" _
, Fix( DateDiff("d", startDate, endDate ) * Rnd ) _
, startDate _
)
End Function
Dim startDate, endDate
startDate = CDate("2016/03/10")
endDate = CDate("2017/09/30")
Dim i
'Call the random number generator with the system time as the seed.
Call Randomize()
For i = 0 To 10
WScript.Echo getRandomDate( startDate, endDate )
Next
1st Output:
14/11/2016
28/09/2016
26/05/2016
06/01/2017
22/09/2016
13/06/2016
12/11/2016
05/03/2017
05/05/2016
01/05/2016
03/02/2017
2nd Output:
08/03/2017
20/01/2017
18/04/2016
29/11/2016
16/08/2016
07/05/2016
06/10/2016
27/01/2017
22/07/2016
19/07/2016
21/09/2017
It's an easy thing to miss but makes a BIG difference.
Dim Date1 As Date, Date2 As Date
Date1 = 10/02/2017
Date2 = 10/06/2017
iDiff = DateDiff("d", Date1, Date2, vbMonday)
Dim RndDate As Date
Randomize
RndDate = DateAdd("d", Int((iDiff * Rnd) + 1), Date1)
I find simple way to generate random Date.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.