Reputation: 3
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.
Upvotes: 0
Views: 585
Reputation: 5500
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);
Upvotes: 2