c# - 在 C# 中格式化可为空的 DateTime
问题描述
我试图从DateTime
可以为空的对象中仅获取日期部分。我试过这个东西
string dueDate = siteRow.DueDate.ToString(cultureInfo.DateTimeFormat.ShortDatePattern)
但它会引发错误:
错误 CS1501 方法“ToString”没有重载需要 1 个参数
上面siteRow.DueDate
是一个 DateTime 对象。我无法弄清楚正确的语法。请帮我解决这个问题。
解决方案
Nullable<T>
是包装 T 类型的通用包装器
它有 2 个属性:Value 和 HasValue。Value 是包装对象的值,HasValue 是一个布尔值,指示在 Value 属性中是否有要获取的值。如果 HasValue 为 true,则 Value 将不是默认值(通常为 null 或空结构)。如果 HasValue 为 false,则 Value 将是默认值。
因此,要访问 DateTime 的 ToString 方法,您需要调用DueDate.Value.ToString
将会
var dueDate = siteRow.DueDate.HasValue ? siteRow.DueDate.Value.ToString(cultureInfo.DateTimeFormat.ShortDatePattern) : null
或使用缩写语法
var dueDate = siteRow.DueDate?.ToString(cultureInfo.DateTimeFormat.ShortDatePattern);
推荐阅读
- r - ggplot图例——如何使线段更长?
- java - 如何在 Eclipse 中使用 Drool 应用程序抑制 INFO 和 WARNING 调试信息
- javascript - Javascript addEventListener() 将表单提交到错误的 php 页面
- python - 为什么镜头注释在 RPC 中返回,但在谷歌存储的 json 文件中不存在?
- python - tokbox python api 房间创建
- c# - 在最后两行中使用未分配的局部变量 fedTax 和 netPay
- javascript - 一种在不知道嵌套 js 对象中的路径的情况下访问属性的方法
- excel - 如何使用 VLOOKUP 返回任何不同的结果?
- spring - 运行 KafkaEmbedded 进行单元测试时出现 java.lang.NoClassDefFoundError
- node.js - 将 Node.js 应用程序上传到 WinSCP 服务器