Simon
Simon

Reputation: 15

Converting short? to TimeSpan

I'm trying to subtract short? Days from DateTime? InitialDate to get DateTime FinalDate.

I'm not sure if, because they are nullable objects, this is causing problems with the comparison. I've tried casting days to a TimeSpan without success.

short? Days = 7;
DateTime? InitialDate = new DateTime(2012, 10, 5);

DateTime FinalDate = InitialDate - Days ;
//FinalDate should be 5/3/2012 12:00 AM

FinalDate should be 5/3/2012 12:00 AM.

Upvotes: 0

Views: 203

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29036

Since both the variables you are dealing with are nullable types, you have to make use of the .Value property of them to access its value. You can also make use of the .HasValue property to check whether it is having any value.

Now comes the subtraction part, I'm not sure what is the role of TimeSpan that you mentioned in the question. But from the output specified and the name of the variable, I assumed that its the number of days. If my understandings are correct, then you can try the following code to subtract the Days from InitialDate to get the FinalDate

For a safe side, you can check whether the InitialDate has a value or not before accessing them.

DateTime? FinalDate = InitialDate.HasValue ? InitialDate.Value.AddDays(-(Days.HasValue? Days.Value : 0)) : null;

This Example may help you to understand things more clear.

Upvotes: 1

Sean
Sean

Reputation: 62532

You can just subtract the Days value from the InitialDate using the AddDays method, passing in the negative value of Days. Since you don't show what you want to happen it either value is null I've made FinalDate nullable:

short? Days = 7;
DateTime? InitialDate = 5/10/2012 12:00 AM;

DateTime FinalDate? = null;
if(Days.HasValue && InitialDate.HasValue)
{
  FinalDate = InitialDate.Value.AddDays(-Days.Value)
}

Upvotes: 1

Related Questions