Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best practice for getting a random DateTime between two date-times?

Tags:

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?

like image 891
Pure.Krome Avatar asked Sep 27 '09 14:09

Pure.Krome


People also ask

How do you generate a random date between two dates?

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).

How do you generate random dates in flutter?

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.


1 Answers

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) DateTimes 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.

like image 158
ChrisF Avatar answered Sep 22 '22 13:09

ChrisF