Reputation: 13763
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?)
How do I get the Day, Month, Year of a nullable datetime?
Upvotes: 16
Views: 23631
Reputation: 113392
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";
Upvotes: 5
Reputation: 89741
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.
Upvotes: 0
Reputation: 5505
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.
Upvotes: 2
Reputation: 100657
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");
Upvotes: 45