我有 1 个不可为 null 的日期时间字段和 1 个可为 null 的日期时间字段。我可以将以下代码与不可为 null 的代码一起使用:
c.StartDate.Day.ToString() + "/" +
c.StartDate.Month.ToString() + "/" +
c.StartDate.Year.ToString()
但是当我尝试对可空的执行此操作时,出现错误:
'System.Nullable' does not contain a definition for 'Day' and no extension method 'Day' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)
如何获取可为 null 的日期时间的日、月、年?
最佳答案
您必须在可为 null 的对象上使用 .Value
属性:
c.StartDate.Value.Day.ToString() //etc
检查完 null
后,您可以:
c.StartDate.Value.ToString("dd-MMM-yyyy");
关于c# - 可为空的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6125163/