1

我正在尝试在 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");
    }
}
4

2 回答 2

2

首先不要使用字符串:

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");
    }
}

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

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

于 2013-04-22T14:02:03.107 回答
0

你可以比较一下:

if(dateTimePicker1.Value==DateTime.Now)

两者都是日期时间。

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

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

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

于 2013-04-22T14:01:14.567 回答