检测从datetime.now开始经过的15分钟时间



我有一个时间选择器,我想知道如何让它检测时间选择器中所选的时间是否比DateTime.Now提前15分钟。

如果我将时间选择器设置为9:15,并且DateTime.Now为9:31,我将收到一条消息,即我只能将时间设置为比实际时间提前15分钟。

您可以使用TimeSpan。。

假设您的日期时间选择器为TimeOnly。。

TimeSpan difftime = DateTimePicker1.Subtract ( now() );
if (difftime.Minutes > 15)
{
    MessageBox.Show("Max 15 Minutes !"); 
}

如果您的日期时间选择器包括日期,那么必须确保.Hours and .Days = 0

只需使用

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

最新更新