Compare date time with a timespan

6

In asp mvc 4, I'm doing a query where I'll get the data where hours are less than or equal to those entered by the user. That is, I have a dateTime and I check with the variable entered by the user (a TimeSpan ) if it is lower or not.

For example:

  • In BD I have the data:

    12-03-2014 12:00:00
    12-03-2014 09:30:00
    12-03-2014 18:00:00'
    

The user enters 10:00 and the result will be only:

12-03-2014 09:30:00

Now I do not know how to make this comparison. I've tried using TimeOfDay but to no avail.

Code:

TimeSpan horaFim = new TimeSpan(10, 00, 00); //Simular variavel introduzida
var plan = db.Planeamento.Where(p => p.DataFimAssitencia.Value.TimeOfDay <= horaFim ).toList();
    
asked by anonymous 18.03.2014 / 16:11

2 answers

3

A time-span is a time interval, and therefore to be transformed into an absolute date needs a basis for calculation. You can use the current date as the basis of calculation like this:

TimeSpan ts = new TimeSpan(10, 00, 00); //Simular variavel introduzida
DateTime tempoFim = DateTime.Now - ts;
var plan = db.Planeamento.Where(p => p.DataFimAssitencia <= tempoFim ).ToList();

EDIT: I think I understand what you want, the problem is to compare only the part of the time in the day.

Assuming you are using the Entity Framework, Do your query like this:

var plan = db.Planeamento.Where(
    p => EntityFunctions.CreateTime(
           p.DataFimAssitencia.Value.Hour,
           p.DataFimAssitencia.Value.Minute,
           p.DataFimAssitencia.Value.Second)
         <= horaFim
     ).ToList();
    
18.03.2014 / 16:18
0

Check the CAST of the p.DataFimAssitencia.Value variable, since you must be receiving a Date and losing the Time. A simple test with the values you passed shows that the output is as expected.

  TimeSpan horaFim = new TimeSpan(10, 00, 00);
  var dates = new List<DateTime>
  {
      new DateTime(2014,3,12,12,00,00),
      new DateTime(2014,3,12,09,30,00),
      new DateTime(2014,3,12,18,00,00)
  };
  var plan = dates.Where(date => date.TimeOfDay <= horaFim).ToList();
    
18.03.2014 / 21:50