Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
C# nullable date
Message
From
25/01/2011 11:17:14
 
 
To
25/01/2011 11:08:04
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Miscellaneous
Thread ID:
01497353
Message ID:
01497368
Views:
34
>>>>>Hi,
>>>>>
>>>>>I want to calculate the age in years so I have this code:
>>>>>
>>>>>
        public static int CalculateAge(DateTime? StartDate, DateTime CurrentDate)
>>>>>        {
>>>>>
>>>>>            int YearsPassed = CurrentDate.Year - StartDate.Year;
>>>>>            // Are we before the birth date this year? If so subtract one year from the mix
>>>>>            if (CurrentDate.Month < StartDate.Month || (CurrentDate.Month == StartDate.Month && CurrentDate.Day < StartDate.Day))
>>>>>            {
>>>>>                YearsPassed--;
>>>>>            }
>>>>>            return YearsPassed;
>>>>>        }
>>>>>
>>>>>I call this code like this:
>>>>>
>>>>>
int policyYear = CalculateAge(this.Entity.IssueDate, DateTime.Now);
>>>>>
>>>>>this.Entity.IssueDate could have a null value. Of course I get errors like this:
>>>>>
>>>>>
'System.Nullable<System.DateTime>' does not contain a definition for 'Year' and no extension method 'Year' accepting a first argument of type 'System.Nullable<System.DateTime>' could be found
>>>>>
>>>>>I've tried putting an if {this.Entity.IssueDate != null} around my call to the function and making th eparameter not nullable, but that hasn't worked. How do I adjust this code to work?
>>>>
>>>>That would depend on what you want to happen when Entity.IssueDate is null........
>>>
>>>If it's null, then I don't want the calculation to be done.
>>
>>Then I guess there's no need to have the method accept a nullable value:
public static int CalcAge(DateTime StartDate, DateTime EndDate)
>>        {
>>//....
>>        }
so
if (IssueDate != null)
>>            {
>>                int age = CalcAge((DateTime)IssueDate, DateTime.Now);
>>            }
>
>Thanks, that's what I ended up doing. :)
>
>Is this way better than what Bonnie suggested?

I don't think its better. AFAIK the difference between IssueDate.HasValue() and IssueDate==null is just a readability issue.
But
DateTime t = IssueDate.Value;
removes the need to cast as in:
DateTime t = (DateTime) IssueDate;
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform