Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to have a kind of method that is in a service that can be accessed by a form so that I can use this method to generate a random date in a date time picker. It just doesn't work however, I have two DTP's called dtp_Current and dtp_New

This is accessed on a form and I have two buttons that say before and after, when before is clicked you are guessing the newly generated date will be before the current date and if you click after it's guessing it's gonna be after the currently generated date. I have to do this using a service however

public int RandomDate()

is what i'd like the method to be called in the Service, how would I go about doing this so when the after button is clicked it checks dtp_Current date to see if dtp_New is larger

I hope this makes sense

summary:
have a form and a service reference
need service reference to generate a random date in dtp_Current
then when before or after is clicked generate a new date in dtp_New
then to check if dtp_New is larger or smaller than dtp_Current



SAVE ME ORIGINALGRIFF
Posted
Updated 24-Mar-14 2:05am
v3
Comments
BillWoodruff 24-Mar-14 8:07am    
So what's stopping you from using the Random object to create random years, months, days, hours, minutes, seconds, and creating DateTime objects from the random values ?

Pretty easy really - DateTime has a constructor that takes a Ticks count: http://msdn.microsoft.com/en-us/library/z2xf7zzk(v=vs.110).aspx[^] so all you need to do is generate a random Int64:
C#
public static Int64 NextInt64(this Random rand)
    {
    var buffer = new byte[sizeof(Int64)];
    rand.NextBytes(buffer);
    return BitConverter.ToInt64(buffer, 0);
    }
You might have to fiddle a bit to get "suitable" values - but that's down to your date range anyway!
 
Share this answer
 
Comments
Member 10603307 24-Mar-14 8:48am    
How would I create a method for a service that generates a random date using this?
OriginalGriff 24-Mar-14 8:56am    
Oh, come on! How difficult is it?
DateTime randomDateTimeValue = new DateTime(random.NextInt64());
Member 10603307 24-Mar-14 9:01am    
Sorry and thanks.

You're like my old teacher D:
OriginalGriff 24-Mar-14 9:02am    
I'll take that as a complement! :laugh:
If you consider that the datetime structure ultimately represents a number of tics, you can generate a random value and use it to initialize a date-time to that number of tics.

DateTime(Int64)

I leave as an exercise for you how to use the appropriate random function to create the value.

 
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