Date formatting on DateTime?

S

Shikari Shambu

I have DateOfBirth declared as

DateTime? DateOfBirth;

DateOfBirth.ToSTring("yyyyMMdd");

gives an error - no overload method ToString() takes 1 arguments.

However, if I were to declare DateOfBirth as

DateTime DateOfBirth;

this works without an error.

How do I get the formatting to work on the nullable DateTime I.e DateTime?
DateOfBirth;

TIA
 
S

Scott Seligman

Shikari Shambu said:
I have DateOfBirth declared as

DateTime? DateOfBirth;

DateOfBirth.ToSTring("yyyyMMdd");

Use DateOfBirth.Value.ToString("yyyyMMdd");
 
S

Shikari Shambu

Figured this out. Have to explicitly give .Value.

DateOfBirth.Value.ToString("yyyyMMdd");
 
B

Bjørn Brox

Shikari Shambu skrev:
I have DateOfBirth declared as

DateTime? DateOfBirth;

DateOfBirth.ToSTring("yyyyMMdd");

gives an error - no overload method ToString() takes 1 arguments.

However, if I were to declare DateOfBirth as

DateTime DateOfBirth;

this works without an error.

How do I get the formatting to work on the nullable DateTime I.e
DateTime? DateOfBirth;
Time to learn about how to use nullable variables?

string text = DateOfBirth.HasValue ?
DateOfBirth.Value.ToString("yyyyMMdd") : "-";
 
G

Geoffrey Summerhayes

I have DateOfBirth declared as

DateTime? DateOfBirth;

DateOfBirth.ToSTring("yyyyMMdd");

gives an error - no overload method ToString() takes 1 arguments.

However, if I were to declare DateOfBirth as

DateTime DateOfBirth;

this works without an error.

How do I get the formatting to work on the nullable DateTime  I.e DateTime?
DateOfBirth;

Check to make sure it's not null, then cast it to DateTime.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top