开发者

nullable datetimes

I have 1 datetime field that is not nullable and 1 that is nullable. I can use the following code with the non nullable one :

 c.StartDate.Day.ToString() + "/" + 
 c.StartDate.Month.ToString() + "/" + 
 c.StartDate.Year.ToString()

But when I try to do this with the nullable one, I get the error :

'System.Nullable' does not contain a definition for 'Day' and no extension method 'Day' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)

开发者_如何学Python

How do I get the Day, Month, Year of a nullable datetime?


You'll have to use the .Value property on your nullable:

c.StartDate.Value.Day.ToString()  //etc

After checking for null, you could:

 c.StartDate.Value.ToString("dd-MMM-yyyy");


if(c.StartDate.HasValue)
{
  DateTime sd = c.StartDate.Value;
  str = sd.Day.ToString() + "/" + sd.Month.ToString() + "/" + sd.Year.ToString()
}
else
  str = "some alternative for when there's no date";

Simpler still:

string str = c.StartDate.HasValue ? c.StartDate.value.ToString(@"d\/M\/yyyy") ? "some alternative for when there's no date";


if(c.EndDate.HasValue)
{
    c.EndDate.Value.Day.ToString() + ...
}

You might also want to check the ToString() of the date and convert it to a string with just one formatting pattern and without concatination.


What would you like the result to be? "//"

You could create extension methods which return "", but you still have the issue of what you want the final result to actually be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜