简体   繁体   中英

Format nullable DateTime in C#

I am trying to fetch only date part from a DateTime object which is nullable. 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

In above siteRow.DueDate is a DateTime object. 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

It has 2 properties: Value and 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. If HasValue is true, then Value will not be the default(usually null or empty struct). If HasValue is false, then Value will be default.

So to access the DateTime's ToString method you need to call 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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