DarkW1nter
DarkW1nter

Reputation: 2841

How to cast to System.Timespan?

can someone tell me how to cast System.Timespan? to System.Timespan I keep getting this error when tryin to get the date difference between the current date and a date from a linq query (see belwo)

System.TimeSpan ts = i.joinDt - DateTime.Now.Date;

Upvotes: 0

Views: 3379

Answers (3)

Oded
Oded

Reputation: 498904

To get a TimeSpan from a TimeSpan? you need to access the Value property of the nullable - no need to cast.

TimeSpan? tsn = i.joinDt - DateTime.Now.Date;
TimeSpan ts;
if(tsn.HasValue)
{
  ts = tsn.Value;
}

Or:

if(i.joinDt.HasValue)
{
  TimeSpan ts = i.joinDt.Value - DateTime.Now.Date;
}

Upvotes: 6

Thomas Levesque
Thomas Levesque

Reputation: 292355

can someone tell me how to cast System.Timespan? to System.Timespan

You need to specify a default value for the case where the TimeSpan? is null:

TimeSpan? nullableTs = ...
TimeSpan ts = nullableTs ?? TimeSpan.Zero;

Upvotes: 4

Bala R
Bala R

Reputation: 108937

System.TimeSpan ts = (i.joinDt - DateTime.Now.Date).Value;

Upvotes: 6

Related Questions