如何在 C# 中比较两个日期的年、月、日、时、分、秒?
我有两个日期,我只想确保它们在这 6 个字段上匹配: 年、月、日、时、分、秒。
我注意到,如果我执行一个简单的 equal == 比较 if(d1 == d2) 匹配这些字段,我仍然得到“false”。我假设这与与刻度、毫秒等相关的其他字段有关。我如何忽略所有内容并确保它们与上面的 6 个字段匹配?
我创建了下面的原型函数,但对我来说,这对于生产级代码来说感觉很业余且效率低下。此外,date1 必须是可为空的日期时间。
还有其他人有更好的建议吗?
private static bool DatesAreEqual(DateTime date1, DateTime date2)
{
var d1 = new DateTime(date1.Year, date1.Month, date1.Day,
date1.Hour, date1.Minute, date1.Second);
var d2 = new DateTime(date2.Year, date2.Month, date2.Day,
date2.Hour, date2.Minute, date2.Second);
return d1 == d2;
}
I have two dates and I only want to make sure they match on these 6 fields:
year, month, day, hour, minute and second.
I have noticed that if I perform a simple equality == comparison if(d1 == d2) that match on these fields, I still get 'false'. I'm assuming this has to do with other fields under the hood that relate to ticks, milliseconds etc. How can I ignore everything and just make sure they match on the 6 fields above?
I have created the prototype function below but to me this feels amateurish and inefficient for production-level code. Furthermore, date1 has to be a nullable datetime.
Does anyone else have any better suggestions?
private static bool DatesAreEqual(DateTime date1, DateTime date2)
{
var d1 = new DateTime(date1.Year, date1.Month, date1.Day,
date1.Hour, date1.Minute, date1.Second);
var d2 = new DateTime(date2.Year, date2.Month, date2.Day,
date2.Hour, date2.Minute, date2.Second);
return d1 == d2;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以删除日期的小数部分(请注意,小数部分比毫秒长):
代码:
您可以实现< em>扩展类以保持主代码更短、更具可读性:
然后
You can remove fractional part of the dates (please, note, that fractional part is longer then just milliseconds):
Code:
You can implement extension class to keep main code shorter and more readable:
And then
如果您检查 TimeSpam,我们会发现
TimeSpan.TicksPerSecond
这是您希望相同的最小值(秒),因此我们将该部分重置为零,并使用刻度进行比较(更快)为:通过这种方式,您只需进行一些数字比较,这是更快的方式。
不仅如此,
基于上面的代码,我还使用选定的 Precision 和 Equal 或 Compare 函数创建了另外两个函数
简单的视觉测试
输出
If you check on the TimeSpam, we have the
TimeSpan.TicksPerSecond
that is the minimum that you want to be the same (the seconds), so we reset that part to zero and we make the compare using ticks (that is the faster) as:With this way you just make some number compare and its the faster way.
More Than That
Base on the above code I also make two more functions with selected Precision and Equal, or Compare functions
Simple Visual Test
output
这可能会稍微快一些:
https://stackoverflow.com/a/58173628/759558
This might be slightly quicker:
https://stackoverflow.com/a/58173628/759558