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
  • 876
  • 1
  • 7
  • 21

4 Answers4

12
if (t1.HasValue)
    string st1 = t1.Value.ToString(format);
abatishchev
  • 95,331
  • 80
  • 293
  • 426
  • 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
  • 44,717
  • 22
  • 115
  • 201
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,509
  • 5
  • 56
  • 83
0

You should check first whether DateTime is null or not

 string strDate = (st1 != null ? st1.Value.ToString(format) : "n/a");
ABH
  • 3,351
  • 22
  • 25