【问题标题】:How do i check if a set time equals the system Time如何检查设定时间是否等于系统时间
【发布时间】:2012-07-03 20:10:44
【问题描述】:

我正在做一个小闹钟作为一个项目来练习,因为我只是一个初学者。

我有 2 个文本框,用户可以在其中输入他希望闹钟响起的小时和分钟。

我如何检查用户提供的闹钟时间是否与他的系统/电脑上的时间相同?

【问题讨论】:

标签: c# datetime clock


【解决方案1】:

使用

int hours = System.DateTime.Now.Hour;
int minutes = System.DateTime.Now.Minute;

if(Convert.Toint32(txtHours.Text) == hours && Convert.Toint32(txtMinutes.Text) == minutes)
{
  // same time 
}
else
{
  // time not same
}

【讨论】:

    【解决方案2】:

    这里有一个小样本可以帮助您上路

        int myMinute = 5;
        int myHour = 19;
    
        if (DateTime.Now.Minute == myMinute && DateTime.Now.Hour == myHour)
        { 
          }
    

    【讨论】:

      【解决方案3】:

      以上所有答案都有帮助,但您应该在实践中使用 TimeSpan 来比较日期或时间。

      int hour=5;
      int min=20;
      int sec=0;
      TimeSpan time = new TimeSpan(hour, min, sec);
      TimeSpan now = DateTime.Now.TimeOfDay;
      // see if start comes before end
      if (time == now)
      {
          //put your condition
      }
      

      请查看此网址了解更多信息。

      How to check if DateTime.Now is between two given DateTimes for time part only?

      【讨论】:

        【解决方案4】:
        var current = DateTime.Now;
        if (current.Hour == 9 && current.Minute == 0) {
            //It is 9:00 now
        }
        

        【讨论】:

          【解决方案5】:
          if(Convert.ToInt32(tbHours.Text) == DateTime.Now.Hours 
          && Convert.ToInt32(tbMinutes.Text) == DateTime.Now.Minutes)
              {
                  //set off alarm
              }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-18
            相关资源
            最近更新 更多