• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 574
  • Last Modified:

DateTime AddHours Interval?

Keep receiving strange datetime (7/1/2336 7:13:47 AM) using RandomInt(.079201111111111) understanding Random returns double.

    private double Randm()
    {          
         Random random = new Random();
         return random.Next(1800000, 36000000); // .5 hour to 10 hours                    
    }

    DateTime dt = DateTime.Now.AddHours(Randm);
    MessageBox.Show(dt.ToString());    
0
pointeman
Asked:
pointeman
  • 4
  • 4
  • 4
  • +2
4 Solutions
 
Todd GerbertIT ConsultantCommented:
Random.Next returns an int.  You're adding 1.8 million hours.
0
 
Todd GerbertIT ConsultantCommented:
0
 
eguilhermeCommented:
?/ if you want to add from .5 to 10 hours use

   private double Randm()
    {          
         Random random = new Random();
         return random.Next(30, 600); // .5 hour to 10 hours                    
    }

    DateTime dt = DateTime.Now.AddMinutes(Randm);
    MessageBox.Show(dt.ToString());  
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
philetaylorCommented:
Hi.

You are assigning a range to Randm of between 1800000 and 36000000

The problem is that you are then using the AddHours method which will be adding between 180000 and 36000000 HOURS to the time!

I think you probably want to use a range of 30 to 600 and use the AddMinutes method instead!

private double Randm()
{          
         Random random = new Random();
         return random.Next(30,600); // .5 hour to 10 hours                    
}

DateTime dt = DateTime.Now.AddMinutes(Randm);
MessageBox.Show(dt.ToString());  

Cheers

Phil
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Here's another way to think about it:
private Random random = new Random();

        private TimeSpan RandomHours(double minHour, double maxHour)
        {
            return TimeSpan.FromMilliseconds(TimeSpan.FromHours(minHour).TotalMilliseconds + (random.NextDouble() * TimeSpan.FromHours(maxHour - minHour).TotalMilliseconds));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now.Add(RandomHours(.5, 10));
            MessageBox.Show(dt.ToString());  
        }

Open in new window

0
 
pointemanAuthor Commented:
I'm also using Randm() method to return values to Windows.Forms.Timer:

    return random.Next(1800000, 36000000); // .5 hour to 10 hours

Came up with the idea to monitor the timers 'fire' time as a second thought.
0
 
pointemanAuthor Commented:
>>The problem is that you are then using the AddHours method which will be adding between 180000 and 36000000 HOURS to the time!

I thought I was using adding approx .079201111111111 or 3/4 hours to the DateTime.AddHours as per original post :)
0
 
philetaylorCommented:
Yes I thought you might!

Here is the definition of the Random.Next Method:

public virtual int Next(
	int minValue,
	int maxValue
)

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
You could also use my post for your Timer, just use the TotalMilliseconds() property of the returned TimeSpan:

    timer1.Interval = RandomHours(.5, 10).TotalMilliseconds;
0
 
pointemanAuthor Commented:
Could also:

private double Randm()
{          
         Random random = new Random();
         return random.Next(30,600); // .5 hour to 10 hours                    
}

DateTime dt = DateTime.Now.AddMinutes(Randm);
MessageBox.Show(dt.ToString());  


Timer timer1 = new Timer();
timer1.Interval = Randm() * 60000; //1800000, 36000000 or .5 hour, 10 hours    
0
 
Todd GerbertIT ConsultantCommented:
I think I would probably just write - complete with the comment, so I know what the heck it's doing when I read the code later:
public partial class Form1 : Form
{
	static Random rand = new Random();

	public Form1()
	{
		InitializeComponent();

		timer1.Interval = rand.Next(30, 600) * 60000; // 30 - 600 minutes (.5 - 10 hours) times 60000 to get millisecs
	}
}

Open in new window


Just seems simpler, more straight forward, to me. *shrug*

(Hopefully my math isn't too wrong)
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
That's why I really like the TimeSpan.FromHours() approach...it's "self documenting":

    timer1.Interval = TimeSpan.FromHours(someHourValue).TotalMilliseconds;

We get a TimeSpan() representing that number of hours (it can accept a double) and then ask it for the total milliseconds that represent that "time span".  No xxx * 60000, or any other value that you have to remember for whatever unit (hours, minutes, seconds) you are looking for.  There are other TimeSpan.FromXXX() methods as well...
0
 
Todd GerbertIT ConsultantCommented:
Agreed, I like that idea better.

Although that other method you posted ealier (http:#a35193935) took me more than a couple scratches of the ole noggin to figure out. ;)
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Lolz...that is just a C# version of this very old formula from the VB6 Rnd() function:
http://msdn.microsoft.com/en-us/library/e566zd96(VS.85).aspx

To produce random integers in a given range, use this formula:

    Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

So my code is:

        private TimeSpan RandomHours(double minHour, double maxHour)
        {
            return TimeSpan.FromMilliseconds(TimeSpan.FromHours(minHour).TotalMilliseconds + (random.NextDouble() * TimeSpan.FromHours(maxHour - minHour).TotalMilliseconds));
        }

The "inner part", inside the outer TimeSpan.FromMilliseconds(), is the formula from the link (just the order of the terms has been reversed):

    TimeSpan.FromHours(minHour).TotalMilliseconds + (random.NextDouble() * TimeSpan.FromHours(maxHour - minHour).TotalMilliseconds)
0
 
pointemanAuthor Commented:
Great Help. Almost ran out of points.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 4
  • 4
  • 4
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now