c# - 可为空的日期时间

标签 c#

我有 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/

相关文章:

c# - 为什么 AppDomain.CurrentDomain.BaseDirectory 的目标是控制台应用程序中的 bincatelog?

c# - 将 DataGrid.ItemSsource 转换为 DataTable

c# - 我可以将对象保存到 app.config 文件吗?

c# - 以编程方式从 .NET Webbrowser Control 的下拉列表中选择一个项目

c# - HasDefaultValue 与从构造函数设置默认值

c# - ASP.NET MVC : Json(IDictionary<string, string>) 转换为键值对数组

c# - 将自定义文本添加到 MVC 5 的下拉列表

C# 符号理解 Select(int.Parse)

c# - 我可以绕过 MVC 应用程序内 Web API Controller 的组织身份验证吗?

c# - 在哪个调度程序 Task.ContinueWith() 上运行?