2012-04-10 3 views
10

tengo un código que lo produce erróneamente y estoy pensando que debe haber una mejor manera de verificar el tiempo> 9.30 a.m. y el tiempo < 4 p. M. . Cualquier idea es muy apreciada.compruebe el tiempo entre 9.30 a 4 ruby ​​

def checkTime 

    goodtime=false 
    if(Time.now.hour>9 and Time.now.min>30) then 

    if(Time.now.hour<16) then 
     goodtime=true 

    else 
     # do nothing 
    end 
    elsif Time.now.hour>9 and Time.now.hour<16 then 
    goodtime=true 

    else 
     # do nothing 
    end 
    return goodtime 

end 

Respuesta

6
t = Time.now 

Range.new(
    Time.local(t.year, t.month, t.day, 9), 
    Time.local(t.year, t.month, t.day, 16, 30) 
) === t 
+0

este funcionó perfecto para mí. muchas gracias. – junkone

+1

No puedo conseguir que funcione en 2.0.0, ya que informa: 'TypeError: no puede iterar desde Time'. La conversión de los puntos finales de rango con '.to_i', y luego la comparación con' t.to_i' funciona, sin embargo. – tamouse

3

Justo:

def checkTime 
    return ((Time.now.hour * 60) + Time.now.min) >= 570 && ((Time.now.hour * 60) + Time.now.min) < 960 
end 
+0

necesito el minuto para ser también mayor que 30 si la hora es <10. ¿Hay alguna forma de comparar hora y minuto como 1 objeto? – junkone

+0

Me sale 'NoMethodError: método indefinido \' minutos 'para 2012-04-10 18:19:18 +0200: Time' –

+0

¿Qué pasa con ((Time.now.hour) * 60) + Time.now.min)? – DanS

5
def check_time(t=Time.now) 
    early = Time.new(t.year, t.month, t.day, 9, 30, 0, t.utc_offset) 
    late = Time.new(t.year, t.month, t.day, 16, 0, 0, t.utc_offset) 
    t.between?(early, late) 
end 
+0

gracias por su respuesta. tuve un problema como ArgumentError: número de argumentos incorrectos (7 para 0) de (irb): 7: en 'initialize ' de (irb): 7: en' nuevo' de (irb): 7 – junkone

3

Trabajar en un entorno de versiones mixtas y que necesitan este método exacto que aquí es lo que he puesto en mi código:

if RUBY_VERSION == "1.9.3" 
    def check_time(starthour,endhour,t=Time.now) 
    early = Time.new(t.year, t.month, t.day, starthour, 0, 0) 
    late = Time.new(t.year, t.month, t.day, endhour, 0, 0) 
    t.between?(early, late) 
    end 
elsif RUBY_VERSION == "1.8.7" 
    def check_time(starthour,endhour,t=Time.now) 
    early = Time.local(t.year, t.month, t.day, starthour, 0, 0) 
    late = Time.local(t.year, t.month, t.day, endhour, 0, 0) 
    t.between?(early, late) 
    end 
end 
Cuestiones relacionadas