Compare date time with a timespan

Asked

Viewed 1,506 times

6

On Asp mvc 4, I’m doing a query where I find the data where the hours are lower or equal than those entered by the user. That is, I have a dateTime and check with the user input variable (a TimeSpan) whether it is inferior or not.

For example:

  • In the comic book I have the data:

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

The user inserts 10:00 and the result will be just:

12-03-2014 09:30:00

Now I don’t know how to make this comparison. I’ve tried using the TimeOfDay but without success.

Code:

TimeSpan horaFim = new TimeSpan(10, 00, 00); //Simular variavel introduzida
var plan = db.Planeamento.Where(p => p.DataFimAssitencia.Value.TimeOfDay <= horaFim ).toList();

2 answers

3


A time-span is a time interval, and therefore to be transformed into an absolute date needs a base calculation. It is possible to use the current date as a basis of calculation thus:

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 on 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();

0

Check the CAST of the variable p.DataFimAssitencia.Value, 'cause you must be getting a date and losing the team. 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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.