Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading