Solved

DateTime AddHours Interval?

Posted on 2011-03-22
15
540 Views
Last Modified: 2012-05-11
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
Comment
Question by:pointeman
  • 4
  • 4
  • 4
  • +2
15 Comments
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35193314
Random.Next returns an int.  You're adding 1.8 million hours.
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35193316
0
 
LVL 10

Accepted Solution

by:
eguilherme earned 63 total points
ID: 35193326
?/ 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 4

Assisted Solution

by:philetaylor
philetaylor earned 63 total points
ID: 35193330
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
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 62 total points
ID: 35193935
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
 

Author Comment

by:pointeman
ID: 35194757
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
 

Author Comment

by:pointeman
ID: 35194770
>>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
 
LVL 4

Expert Comment

by:philetaylor
ID: 35194787
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35194789
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
 

Author Comment

by:pointeman
ID: 35195156
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
 
LVL 33

Assisted Solution

by:Todd Gerbert
Todd Gerbert earned 62 total points
ID: 35195206
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35195343
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
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35195404
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35195457
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
 

Author Closing Comment

by:pointeman
ID: 35197865
Great Help. Almost ran out of points.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Connection String 16 58
C#  Radio button search for Date not DateTime 4 46
Reference issues in Visual Studio 3 30
Winform Module - What is the ASP.Net equiv 2 21
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question