5

Possible Duplicate:
How can I format a nullable DateTime with ToString()?

got issue parsing DateTime? to specific format. Like:

 DateTime t1 = ...;
 string st1 = t1.ToString(format); //<-- works

 DateTime? t1 = ...;
 string st1 = t1.ToString(format); //Dont work.

Theres no overload method for DateTime?

Community
  • 1
  • 1
VoonArt
  • 884
  • 1
  • 7
  • 21

4 Answers4

12
if (t1.HasValue)
    string st1 = t1.Value.ToString(format);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • http://stackoverflow.com/questions/1833054/how-can-i-format-a-nullable-datetime-with-tostring My Bad. Close/delete, please. Sorry – VoonArt May 15 '12 at 12:24
3

Use Coalesce Operator

DateTime? t1 = ...;

string st1 = t1 ?? t1.Value.ToString(format);
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

you can try like this , nullabale type has the property called hasValue Nullable has Value

if (t1.HasValue)
   t1.Value.ToString(yourFormat)
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
0

You should check first whether DateTime is null or not

 string strDate = (st1 != null ? st1.Value.ToString(format) : "n/a");
ABH
  • 3,391
  • 23
  • 26