可以约会的日期

use*_*406 16 c#

我有1个不可空的日期时间字段和1可以为空的日期时间字段.我可以使用以下代码与非可空的代码:

 c.StartDate.Day.ToString() + "/" + 
 c.StartDate.Month.ToString() + "/" + 
 c.StartDate.Year.ToString()
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用可空的那个时,我得到错误:

'System.Nullable'不包含'Day'的定义,并且没有扩展方法'Day'接受类型'System.Nullable'的第一个参数可以找到(你是否缺少using指令或汇编引用?)

如何获得可以为空的日期时间的日,月,年?

p.c*_*ell 38

您必须使用.Value可空的属性:

c.StartDate.Value.Day.ToString()  //etc
Run Code Online (Sandbox Code Playgroud)

检查后null,您可以:

 c.StartDate.Value.ToString("dd-MMM-yyyy");
Run Code Online (Sandbox Code Playgroud)

  • 但如果需要,请先检查HasValue (8认同)
  • 我还会添加一个空检查或使用.GetValueOrDefault()是安全的. (2认同)

Jon*_*nna 5

if(c.StartDate.HasValue)
{
  DateTime sd = c.StartDate.Value;
  str = sd.Day.ToString() + "/" + sd.Month.ToString() + "/" + sd.Year.ToString()
}
else
  str = "some alternative for when there's no date";
Run Code Online (Sandbox Code Playgroud)

更简单:

string str = c.StartDate.HasValue ? c.StartDate.value.ToString(@"d\/M\/yyyy") ? "some alternative for when there's no date";
Run Code Online (Sandbox Code Playgroud)