I'm trying to randomize the value for a simple DateTime
data field.
I wish to get a random date/time between two date/times (e.g. min date/time and max date/time).
So lets imagine I'm after a random date/time between
1/1/2000 10:00:00am
and 1/1/2000 5:00:00pm
.
Also, this code will be used in a for loop, with 100 items ... meaning all 100 items will have random date/times between the min/max date/time period.
Any ideas?
To generate random dates between two dates, you can use the RANDBETWEEN function, together with the DATE function. This formula is then copied down from B5 to B11. The result is random dates between Jan 1, 2016 and Dec 31, 2016 (random dates in the year 2016).
import 'dart:math'; var now = new DateTime. now(); Random rnd = new Random(); Random rnd2 = new Random(now. millisecondsSinceEpoch); void main() { int min = 13, max = 42; int r = min + rnd.
You could try using:
var randomTest = new Random(); TimeSpan timeSpan = endDate - startDate; TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0); DateTime newDate = startDate + newSpan;
This will give you different times down to the minute. If you want 100 (or any thing more than 1) DateTime
s then only create the Random
object once. The MSDN page on Random
explains in detail why creating several Random
objects in quick succession is a bad idea.
Using a different TimeSpan
constructor will give you different granularity. From the TimeSpan constructor MSDN:
TimeSpan(Int64) Initializes a new TimeSpan to the specified number of ticks.
TimeSpan(Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of hours, minutes, and seconds.
TimeSpan(Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, and seconds.
TimeSpan(Int32, Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, seconds, and milliseconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With