如何检查是否输入了日期

时间:2014-01-23 15:19:41

标签: c# date

我有一个方法:

public IEnumerable<Something> MethodName(DateTime? checkin, DateTime? checkout, int year){}

通过此方法,我如何检查用户是否输入了签入日期。这就是我所做的,但我得到一个错误:我想我没有使用正确的操作员来检查日期。

   if (checkin.HasValue){
List<Name> l =FileName.NameofMethod(checkin)
} else if (checkin.HasValue && checkout.HasValue){
List<Name> l =FileName.NameofMethod2(checkin, checkout, year)
}

如果我返回列表,这种方法会有效吗?目前我收到一个错误说:

Error   8   The best overloaded method match for 'ProjectName.FileName.NameofMethod(System.DateTime, System.DateTime, int)' has some invalid arguments 

我也得到错误:

Error   9   Argument 1: cannot convert from 'System.DateTime?' to 'System.DateTime'

这意味着什么。因此,如果选择了一个日期,则在选择了两个日期时触发方法,然后触发另一个执行其他操作的方法

1 个答案:

答案 0 :(得分:2)

您应该使用DateTime吗?而不是DateTime类型。 '?'使DateTime可以为空,因此如果没有输入数据,它将包含null。

因此,您的方法签名将如下所示:

public IEnumerable<Something> MethodName(DateTime? checkin, DateTime? checkout, int year){}

然后,您可以将if-condition更改为以下内容:

if (checkin.HasValue)
{
   //do something....
} 
else if (checkin.HasValue && checkout.HasValue)
{
   //do something else...
}

如果您不想更改类型,可以将其与DateTime.MinValue进行比较

if(checkin != DateTime.MinValue)

由于这是DateTime的默认值,因此如果用户不设置任何内容,将为checkin分配此值。

相关问题