How to calculate an hour a and an hour b with time ruby

0

I'm doing a validation that has to be longer than 4 hours and I do not know how to do it.

I have two attributes hora_inicio and hora_final , which belong to Time .

In the first validation:

def validar_horas
  if hora_inicio < hora_final

  else
    errors.add(:hora_final,"La hora final de la reunion debe ser mayor a la de hora inicial")      
  end
end

The second not I know how it's done, I've tried to do everything.

    
asked by MIGUEL ANGEL GIL RODRIGUEZ 05.06.2017 в 18:39
source

3 answers

1

The difference between two instances of Time is a float in seconds, so that you can make the following comparison,

( hora_final - ( 60 * 60 * 4 ) ) < ( hora_inicio )
    
answered by 05.06.2017 / 19:26
source
0

I would do it this way:

if (hora_final - hora_inicio) / 3600 > 4
  # ...
else
  errors.add(:hora_final,"La hora final de la reunion debe ser mayor a la de hora inicial") 
end

The previous code works, but if you are not going to take any action when the if is met (ie hora_final is greater by 4 hours at hora_inicial ), then I recommend you reverse the logic and reduce your code:

if (hora_final - hora_inicio) / 3600 <= 4
  errors.add(:hora_final,"La hora final de la reunion debe ser mayor a la de hora inicial")
end

Or, failing that, use unless instead of if :

unless (hora_final - hora_inicio) / 3600 > 4
  errors.add(:hora_final,"La hora final de la reunion debe ser mayor a la de hora inicial") 
end
    
answered by 05.06.2017 в 19:44
0

I propose the following, I think it is more readable.

def validar_horas

  if hora_inicio > hora_final - 4.hours
    errors.add(:hora_final, "La hora final de la reunion debe ser al menos 4 horas posterior a la hora inicial")      
  end

end

If you think it's clearer, you can turn the condition upside down:

if hora_final - 4.hours < hora_inicio

Or add the four hours at the beginning instead of subtracting them at the end:

if hora_inicio + 4.hours > hora_final

All three conditions give the same result.

    
answered by 13.06.2017 в 00:49