Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi

randomly want to generate date.the date may be anydates..
it takes pastyear, present year ,future year..it want to generate any date
Posted

public DateTime GetRandomDate()
{

DateTime from = new DateTime(1950, 1, 1);
DateTime to = new DateTime(2050, 12, 31);

TimeSpan range = new TimeSpan(to.Ticks - from.Ticks);
return from + new TimeSpan((long)(range.Ticks * rnd.NextDouble()));
}

Found correct solution..
 
Share this answer
 
So? Use the Random class:
private Random rand = new Random();
private void button1_Click(object sender, EventArgs e)
     {
     DateTime randomDate = new DateTime(rand.Next(1066, 2188), rand.Next(1, 13), rand.Next(1, 32));
     }
You will probably want to add some error checking, as this will throw an exception on 31st April and so forth, but otherwise it will generate a random date in the years 1066 to 2187 inclusive.
 
Share this answer
 
Just change the range or operation in adddays in
Hi how to generate a random date ?[^]
It is your question only.

Try something on your own, then only post the question.
 
Share this answer
 
v2
Comments
suryaswathi 4-Jul-11 5:52am    
I tried my function .in that i am getting error..thatsy posted.am also fresher
Prerak Patel 4-Jul-11 5:55am    
Then show what you tried. We can point out the errors.
suryaswathi 4-Jul-11 6:16am    
public DateTime GetRandomDate()
{


DateTime from = new DateTime(1950, 1, 1);
DateTime to = new DateTime(2050, 12, 31);


TimeSpan range = new TimeSpan(to.Ticks - from.Ticks);
return from + new TimeSpan((long)(range.Ticks * rnd.NextDouble()));
}

this is my function ..now its working correct..before that
i didnt give the representation new DateTime in this line

DateTime from = new DateTime(1950, 1, 1);

so that i got error .i gave oly the variable dates

now myself cleared the error
Prerak Patel 4-Jul-11 6:19am    
That's great. Keep going.
suryaswathi 4-Jul-11 6:19am    
thanks....
Sincerely there are 1000 solutions to this problem, you need to be more specific on what you want to achieve.

However do not forget http://tinyurl.com/6fnww4y[^]

One possible solution can be:

DateTime RandomDay()
    {
        DateTime start = new DateTime(1995, 1, 1);
        Random gen = new Random();
        int range = ((TimeSpan)(DateTime.Today - start)).Days;           
        return start.AddDays(gen.Next(range));
    }


Cheers!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900