# 从datetime.now检测到经过15分钟的时间

detect 15 minutes elapsed time from datetime.now
2021-07-22
•  译文(汉语)
•  原文(英语)

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

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

`TotalMinutes`.或者`difftime > TimeSpan.FromMinutes(15)`

.. thanx

``````// 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;
}
``````

-您在使用什么叫"时间选择器"?我一直在假设一个DateTimePicker对象,它是我能找到的最接近的对象...

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.

Solutions1

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`

Talk1:
`TotalMinutes`. Or `difftime > TimeSpan.FromMinutes(15)`
Talk2:
.. thanx
Solutions2

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;
}
``````
Talk1:
I added some more text to my question before i got your answer
Talk2:
I slightly modified the code for relevance but my answer is mostly the same. Please tell me if you have any trouble implementing it! (If you do, please say specifically what's going wrong)
Talk3:
I am getting to errors that are the following: The best overloaded method match for 'System.DateTime.Subtract(System.TimeSpan)' has some invalid arguments and the next error is: Argument 1: cannot convert from 'System.DateTime?' to 'System.TimeSpan'
Talk4:
- what are you using that you called 'timepicker'? I've been assuming a DateTimePicker object, which is the closest that I can find...
Talk5:
oh wait, you seem to have made your variable nullable somehow. Possibly a .net 4.5 thing... er, add a `.Value` to the end of the argument to the `.Subtract` (What I have as `timepicker.Value`) - even if that means you have a `.Value.Value` - if that's no help, could you please post the code you're using? (Including any changes you made from what I wrote)