【问题标题】:Active between a range of times在一定时间范围内活跃
【发布时间】:2015-07-11 10:46:21
【问题描述】:

有没有办法在 c# 中的一段时间内激活消息框。例如,我可以在 13:00 和 16:00 期间显示一个消息框吗?

if(DateTime.TimeOfDay(13,0,0 to 16,0,0)
{
    messagebox.show("You need to feed the dog now");
}

如果你有解决这个问题的方法,请告诉我,因为我已经被这个问题困扰了一段时间。

这是我目前的代码。

if(theDate.TimeOfDay <= new TimeSpan(11,59,0))
            {
                synthesizer.SpeakAsync("Good Morning");
            }
            else if(theDate.TimeOfDay >= new TimeSpan(17, 0, 0))
            {
                synthesizer.SpeakAsync("Good Evening");
            }
            else if(theDate.TimeOfDay > new TimeSpan(12, 0, 0) && theDate.TimeOfDay < new TimeSpan(16, 59, 0))
            {
                synthesizer.SpeakAsync("Good Afternoon.");
            }

【问题讨论】:

  • 到底是什么问题?你甚至都没有告诉我们。您认为我们如何在不知情的情况下解决它?
  • 当我运行这段代码时,它一直说“早上好”,而不是跳过那个并转到“下午好”
  • 你调试过你的代码,看看你的theDate.TimeOfDay到底是什么?
  • 是的,我已经这样做了,没有错误。

标签: c# windows forms datetime if-statement


【解决方案1】:

您可以轻松地使用&lt;&gt; 运算符来比较您的TimeSpan 值,例如;

var ts = DateTime.Now.TimeOfDay;
if(ts > new TimeSpan(13, 0, 0) && ts < new TimeSpan(16, 0, 0))
{
     MessageBox.Show("You need to feed the dog now");
}

【讨论】:

  • @Sachin doesn't work永远足以解释您的问题的信息。你得到任何错误或异常?提问时应显示所有相关代码。
  • if(theDate.TimeOfDay = new TimeSpan(17, 0, 0)) { synthesizer.SpeakAsync("晚安"); } else if(theDate.TimeOfDay > new TimeSpan(12, 0, 0) && theDate.TimeOfDay
  • 对不起,如果不清楚,但这是我到目前为止所拥有的,
  • @Sachin 用edit button更新你的问题。
【解决方案2】:

如果你只是使用小时作为限制,你也可以这样做:

int thisHour = DateTime.Now.Hour;
if(thisHour.CompareTo(13 - 1) + thisHour.CompareTo(16) == 0)
{
    MessageBox.Show("You need to feed the dog now.");
}

或者,关于您的扩展任务:

int thisHour = DateTime.Now.Hour;
string salutation = "Good Evening";

if(thisHour < 12)
{
    salutation = "Good Morning";
}
else if (thisHour < 17)
{
    salutation = "Good Afternoon";
}
synthesizer.SpeakAsync(salutation);

【讨论】:

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