In this example, I’ll show you How to generate a random date between Jan 1 1970 and the current date.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class RandomDateTime { DateTime start; Random gen; int range; public RandomDateTime() { start = new DateTime(1970, 1, 1); gen = new Random(); range = (DateTime.Today - start).Days; } public DateTime Next() { return start.AddDays(gen.Next(range)).AddHours(gen.Next(0,24)).AddMinutes(gen.Next(0,60)).AddSeconds(gen.Next(0,60)); } } |
This C# code creates a class called “RandomDateTime”. The purpose of this class is to generate a random date and time within a specified range.
The class has three instance variables:
- “start” is a DateTime object that stores the start date, which is set to January 1, 1970.
- “gen” is a Random object that generates random numbers.
- “range” is an integer that represents the number of days between the start date and the current date.
The class has a constructor that initializes the start date, the random number generator, and the range of days.
The class also has a method called “Next” that generates and returns a random date and time. This method uses the “AddDays”, “AddHours”, “AddMinutes”, and “AddSeconds” methods to add a random number of days, hours, minutes, and seconds to the start date, respectively. The range of the values generated by the random number generator is specified as arguments to these methods.
And example how to use to write 10 random DateTimes to console:
1 2 3 4 5 6 7 8 9 10 11 | static void Main(string[] args) { RandomDateTime date = new RandomDateTime(); for (int i = 0; i < 10; i++) { Console.WriteLine(date.Next()); } Console.ReadKey(); } |
Output: