Robin M
Robin M

Reputation: 41

detect 15 minutes elapsed time from datetime.now

I have a timepicker and I wonder how I can make it detect if the selected time in the timepicker is 15 minutes ahead of the DateTime.Now.

If I set the timepicker to 9:15 and the DateTime.Now is 9:31 I should get a message that I only can set the time 15 minutes ahead the actual time.

Upvotes: 0

Views: 1878

Answers (2)

matzone
matzone

Reputation: 5719

You may use TimeSpan ..

Assumed that your datetimepicker is TimeOnly ..

TimeSpan difftime = DateTimePicker1.Subtract ( now() );

if (difftime.Minutes > 15)
{
    MessageBox.Show("Max 15 Minutes !"); 
}

If your datetimepicker including date, so must ensure that .Hours and .Days = 0

Upvotes: 1

mcmonkey4eva
mcmonkey4eva

Reputation: 1377

Just use

// In the timepicker's time-changed event
if (DateTime.Now.CompareTo(timepicker.Value) == 1 && DateTime.Now.Subtract(timepicker.Value).TotalMilliseconds > 15 * 60 * 1000)
{
     // Do stuff!
     MessageBox.Show("You can only set a max of 15 minutes ahead of the current time!");
     // Cancel the event / set the timepicker's value back to the current time / whatever you prefer
     // One option:
     timepicker.Value = DateTime.Now;
}

Upvotes: 0

Related Questions