营地日期时间问题 [英] Problem in campareing datetime
问题描述
DateTime dt = DateTime.Parse(label10.Text);
long t = dt.ToFileTime();
DateTime date1 = DateTime.Today;
DateTime date2 = new DateTime(t);
// DateTime date2 = new DateTime(Convert.ToInt64(label10.Text));
// DateTime date2 = new DateTime(2015,9,16);
int result = DateTime.Compare(date1,date2);
字符串关系;
if(结果> 0)
{
relationship =早于;
// SendEmail();
}
else if(result == 0)
{
relationship =与...同时;
SendEmail();
//MessageBox.Show(相同);
}
其他
{
relationship =晚于;
SendEmail();
//MessageBox.Show(以后是);
}
Console.WriteLine({0} {1} {2},date1,relationship,date2);
现在问题是当我运行应用程序时,date2被填充29.09.15而标签10显示为30.09.15。我不明白为什么会发生这种情况
确定 - 永远不要将DateTime值与绝对相等进行比较:它们是精确到刻度 [ ^ ],这是百万分之一的一秒钟。
这意味着在实践中,你的代码很可能恰好匹配相等。
相反,请考虑检查差异:
Timespan diff = date1 - date2;
if (diff.TotalSeconds < 0 )
...
else if (diff.TotalSeconds == 0 )
...
else
.. 。这至少会给你一个与其匹配的一秒钟窗口(或者如果你的计时器不准确,则使用TotalMinutes)
hii i am facing a problem in my code in which i am comparing today's date with the date in database this is my code. Here label10.Text is containing the date from database. Basically i am making a reminder app. If the database date matches with todays date then it should send a reminder email
DateTime dt = DateTime.Parse(label10.Text); long t = dt.ToFileTime(); DateTime date1 = DateTime.Today; DateTime date2 = new DateTime(t); //DateTime date2 = new DateTime(Convert.ToInt64(label10.Text)); //DateTime date2 = new DateTime(2015,9,16); int result = DateTime.Compare(date1, date2); string relationship; if (result > 0) { relationship = "is earlier than"; //SendEmail(); } else if (result == 0) { relationship = "is the same time as"; SendEmail(); //MessageBox.Show("is same"); } else { relationship = "is later than"; SendEmail(); //MessageBox.Show("is later"); } Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
Now the problem is when i run the application the date2 gets filled with 29.09.15 whereas label 10 shows 30.09.15. i am not getting why it is happening
OK - never compare DateTime values for absolute equality: they are accurate to a tick[^], which is one ten millionth of a second.
That means that in practice there is very, very little chance that your code will ever match equality precisely.
So instead, consider checking the difference:
Timespan diff = date1 - date2; if (diff.TotalSeconds < 0) ... else if (diff.TotalSeconds == 0) ... else ...That at least gives you a one-second window in which it will match (or if your timer is not that accurate, use TotalMinutes instead)
这篇关于营地日期时间问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!