C# 如何测试两个日期时间是否相同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11092022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test two dateTimes for being the same date?
提问by B. Clay Shannon
Possible Duplicate:
How to compare Dates in C#
可能的重复:
如何在 C# 中比较日期
This code of mine:
我的这个代码:
public static string getLogFileNameForDate(DateTime dt)
{
if (dt.Equals(DateTime.Now))
...fails even when the two dates are the same (date) because dt is assigned a value at startup (e.g. "6/18/2012 15:19:42"), and so the dates are not exactly the same, even though the year, month, and day are the same (value of DateTime.Now may be, say, "6/18/2012 15:30:13").
...即使两个日期相同(日期)也会失败,因为 dt 在启动时分配了一个值(例如“6/18/2012 15:19:42”),因此日期不完全相同,即使尽管年、月和日是相同的(DateTime.Now 的值可能是“6/18/2012 15:30:13”)。
I know I can test it this way:
我知道我可以这样测试:
if ((dt.Year.Equals(DateTime.Now.Year) && (dt.Month.Equals(DateTime.Now.Month) && (dt.Day.Equals(DateTime.Now.Day))
...but that seems a bit Jethro*-like
...但这似乎有点像 Jethro*-like
What is the accepted/preferred method (no pun intended)?
什么是公认的/首选的方法(没有双关语)?
- Clampett, not Tull
- 克兰佩特,不是塔尔
采纳答案by Brandon
Try
尝试
if (dt.Date == DateTime.Now.Date)
It will only take the date portion and the timestamp will be 12:00:00
它只会取日期部分,时间戳将为 12:00:00

