Sunday, 3 March 2013

Generate Random Date using C#

Generate Random Date using C#


This example generates random date from 1900 to 9999.   
if Month is February checks for Leap year so days will 29 otherwise 28.

        DateTime GenererateRandomDate()
        {
          
            int year = rnd.Next(1900, 9999);
            int month = rnd.Next(1, 12);
            int day = DateTime.DaysInMonth(year,month);
          
            int Day = rnd.Next(1, day);

            DateTime dt = new DateTime(year,month,Day);
            return dt;
        }

Construct Random Class object Outside of the function,Make n number of calls.




OUTPUT:

Random Date=10/11/5427 12:00:00 AMRandom Date=6/22/4602 12:00:00 AMRandom Date=9/7/7710 12:00:00 AMRandom Date=10/12/7657 12:00:00 AMRandom Date=8/23/2410 12:00:00 AM
 

Note: User can apply  Standard Date Formats on this.

for ex:  rndDate.ToString("d")   displays short date:  2/18/5335 

other available formats are: o,O,g,G,d,D,s,u,U,f,F,Y,y .


Tags: Generate Random Dates in C#,  Generate Random Dates in various format,Random Date in C#.Generate Random Month,Generate random Day,Generate Random Year,How to Generate Random DateTime Object,Generate Random UTC Dates

No comments:

Post a Comment