如何比较c#中的日期

sha*_*afi 58 c# datetime

我有两个约会.一个日期是输入,另一个是DateTime.Now.我有它们的mm/dd/yyyy格式,它甚至可以是m/d/yy格式.两个日期都可DateTime?以为空,即数据类型是,因为我也可以将null作为输入传递.现在我想只用mm/dd/yyyym/d/yy格式比较两个日期.

Dam*_*ver 81

如果你有你的日期在日期时间变量,他们不具备的格式.

您可以使用该Date属性返回DateTime值,并将时间部分设置为午夜.所以,如果你有:

DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;

if(dt1.Date > dt2.Date)
{
     //It's a later date
}
else
{
     //It's an earlier or equal date
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你不需要小时,分钟等,最好使用`DateTime.Today`而不是`DateTime.Now.Date` (13认同)
  • @Arbaaz - 一旦你把你所拥有的*字符串*转换为'DateTime`,那么正如我在回答中所说,它不再*具有*格式.它有一个内部表示,框架知道如何进行适当的比较. (3认同)

FIr*_*nda 31

如果您在DateTime变量中有日期,那么它是一个DateTime对象,并且不包含任何格式.格式化日期表示为string调用DateTime.ToString方法并在其中提供格式时.

假设你有两个DateTime变量,你可以使用compare方法进行比较,

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";
Run Code Online (Sandbox Code Playgroud)

代码片段取自msdn.


BC.*_*BC. 8

首先,要了解DateTime对象没有格式化.它们只将年,月,日,小时,分钟,秒等存储为数值,并且当您想要以某种方式将其表示为字符串时,格式化会发生.您可以比较DateTime对象而不格式化它们.

要比较输入日期DateTime.Now,您需要先将输入解析为日期,然后再比较年/月/日部分:

DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
    throw new ArgumentException("Input string not in the correct format.");

if(inputDate.Date == DateTime.Now.Date) {
    // Same date!
}
Run Code Online (Sandbox Code Playgroud)