【问题标题】:time reminder application C#时间提醒应用程序 C#
【发布时间】:2013-04-22 13:56:16
【问题描述】:

我正在尝试在 C# - Visual Studio 2010 中制作一个应用程序。这个应用程序就像一个提醒。您将便笺放入文本框中,并使用DateTimePicker 选择何时需要提醒事情。
问题是我不知道该怎么做。

我已经从 DatetimePicker 中选择了日期和时间:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd/MM/yyyy HH:mm:ss";

现在我需要将 datetimePicker 中的时间与当前日期和时间进行比较,如果值相同,则显示带有一些文本的消息按钮。

我不确定是否可以使用计时器以及如何比较这些值?像这样的东西:-)

string timese = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
string theDay = dateTimePicker1.Value.ToShortDateString();

private void timer1_Tick(object sender, EventArgs e)
{
    if (theDay == theDay2)
    {
        MessageBox.Show ("Reminder");
    }
}

【问题讨论】:

  • 您能帮我找出代码中的问题吗? ` private DateTime theDay; private void button6_Click(object sender, EventArgs e) { DateTime theDay = dateTimePicker1.Value;图片框3.可见=真; MessageBox.Show("数据已保存"); timer1.Enabled = true; } private void timer1_Tick(object sender, EventArgs e) { if (DateTime.Now.CompareTo(theDay) > 0 ) // 检查现在是否在 theDay 之后 { theDay = DateTime.MaxValue; timer1.Enabled = false; MessageBox.Show(“提醒”)`

标签: c# timer alarm


【解决方案1】:

首先不要使用字符串:

DateTime theDay = dateTimePicker1.Value;

private void timer1_Tick(object sender, EventArgs e)
{
    if (DateTime.Now.CompareTo(theDay) > 0 ) // checks if now is after theDay
    {
        theDay = DateTime.MaxValue;
        // makes sure there wont be multiple MessageBox due to event queuing
        // you could also just stop the timer here
        MessageBox.Show ("Reminder");
    }
}

不建议日期完全匹配 (==),因为计时器可能会跳过确切的时间并且永远不会是真的。

编辑:我的比较是错误的方式,现在应该是正确的

【讨论】:

  • 谢谢,这似乎正是我所需要的。但是我有一个问题,也许仍然很愚蠢..当我使用这个时: private void button1_Click(object sender, EventArgs e) { DateTime theDay = dateTimePicker1.Value;} private void timer1_Tick(object sender, EventArgs e) { if (DateTime .Now.CompareTo(theDay) > 0 ) { theDay = DateTime.MaxValue; MessageBox.Show("提醒");它显示错误:当前上下文中不存在名称“theDay”。我想我必须在其他地方定义 theDay ......请解释一下我在哪里以及如何?在公共部分课程中?
【解决方案2】:

你可以比较一下:

if(dateTimePicker1.Value==DateTime.Now)

两者都是日期时间。

但是上面的代码有一个问题。它将时间与毫秒进行比较,可能永远不会相同。因此,您可以将代码更改为类似

if(dateTimePicker1.Value-DateTime.Now).TotalSeconds<2)

(DateTime1 - DateTime2) is timepan more abote this class is on MSDN

【讨论】:

  • 计时器必须以完全相同的毫秒计时才能工作。非常糟糕的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多