Generate Random Date in C# – Programming, Pseudocode Example, C# Programming Example
C# C# Console

Generate Random Date in C#

In this example, I’ll show you How to generate a random date between Jan 1 1970 and the current date.

C# Code:

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:

Output:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.