简体   繁体   English

在 C# 中格式化可为空的 DateTime

[英]Format nullable DateTime in C#

I am trying to fetch only date part from a DateTime object which is nullable.我试图从可为空的DateTime对象中仅获取日期部分。 I tried this thing我试过这个东西

string dueDate = siteRow.DueDate.ToString(cultureInfo.DateTimeFormat.ShortDatePattern)

But it throws error:但它抛出错误:

Error CS1501 No overload for method 'ToString' takes 1 arguments错误 CS1501 方法“ToString”没有重载需要 1 个参数

In above siteRow.DueDate is a DateTime object.在上面的siteRow.DueDate是一个 DateTime 对象。 I am not able to figure out the correct syntax.我无法弄清楚正确的语法。 Please help me out in this.请帮我解决这个问题。

Nullable<T> is the generic wrapper that wraps the T type Nullable<T>是包装 T 类型的通用包装器

It has 2 properties: Value and HasValue.它有两个属性:Value 和 HasValue。 Value is the value of the wrapped object and HasValue is a boolean that indicates if there is a value to obtain in the Value property. Value 是包装对象的值,HasValue 是一个布尔值,指示是否在 Value 属性中获取值。 If HasValue is true, then Value will not be the default(usually null or empty struct).如果 HasValue 为 true,则 Value 将不是默认值(通常为 null 或空结构)。 If HasValue is false, then Value will be default.如果 HasValue 为 false,则 Value 将是默认值。

So to access the DateTime's ToString method you need to call DueDate.Value.ToString所以要访问 DateTime 的 ToString 方法,您需要调用DueDate.Value.ToString

would be将是

var dueDate = siteRow.DueDate.HasValue ? siteRow.DueDate.Value.ToString(cultureInfo.DateTimeFormat.ShortDatePattern) : null

or using the abbreviated syntax或使用缩写语法

var dueDate = siteRow.DueDate?.ToString(cultureInfo.DateTimeFormat.ShortDatePattern);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM