-2

I'm trying to get the difference between two dates, but I get this error:

Cannot Convert type 'int?' to 'System.TimeSpan'

Then I tried to use Convert.ToInt32() or Int32.Parse(), but still had the same error. Can anyone please help me or point me in the right direction?

ViewModel:

 public class RMACLOSE
 {
     public TimeSpan? diff { get; set; }
 }

Controller:

var list = from RH in RMA_History
select new RMACLOSE 
{
    // Cannot Convert type 'int?' to 'System.TimeSpan?'
    diff = DbFunctions.DiffDays(RH.EndDate, RH.StartDate) 
}

RH.EndDate (DateTime): 2018-11-15 12:15:00.000
RH.StartDate (DateTime): 2018-05-24 15:43:00.000

Difference : 175 days

CarenRose
  • 1,266
  • 1
  • 12
  • 24
The First
  • 139
  • 2
  • 13
  • 4
    It's complaining that you're giving it an `int?` when it wants a `TimeSpan?`. Why would you think methods that *produce* an `int` would be part of the solution here? Your problem is you have too many of those to start with. – Damien_The_Unbeliever Jan 14 '19 at 08:48
  • could you please show how your data look like in `RH.EndDate, RH.StartDate` – er-sho Jan 14 '19 at 08:49
  • 1
    You have literally shown *everything except the most pertinent parts of the code*. – Ian Kemp Jan 14 '19 at 08:59
  • @er-mfahhgk i updated my question :) – The First Jan 14 '19 at 09:08
  • 1
    I think you need the difference between both date and i.e. `175` so why you could not use `int?` type of `diff` property inside `RMACLOSE` class so might be your error becomes solved and then you don't need any type casting – er-sho Jan 14 '19 at 10:04
  • @er-mfahhgk thanks mate it works :) and i deserved -2 down vote :) i understand why! if you dont mind post answer i will mark as right answer – The First Jan 14 '19 at 10:11
  • @Damien_The_Unbeliever you were right :) – The First Jan 14 '19 at 10:16
  • @TheFirst, answer added, and upvoted to your question :) – er-sho Jan 14 '19 at 10:18

2 Answers2

1

It is evident from the error message that DbFunctions.DiffDays() returns an int? (that presumably represents the time difference in days).

Therefore you will need to do something like this to convert it into TimeSpan?:

var days = DbFunctions.DiffDays();

if (days != null)
    diff = TimeSpan.FromDays(days.Value);
else
    diff = null;
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

I think you need the difference between both date means EndDate and StartDate and i.e. 175,

So why you could not use int? type of diff property inside RMACLOSE class like

public class RMACLOSE
{
    public int? diff { get; set; }
}

And might be your error becomes solved and then you don't need any type casting and you simply use your LINQ query as it is like

select new RMACLOSE 
{    
  diff = DbFunctions.DiffDays(RH.EndDate, RH.StartDate)   
}

DbFunctions.DiffDays returns int? so it matches your diff property type and then no error will remain.

er-sho
  • 9,581
  • 2
  • 13
  • 26