How to subtract two dates using Ruby and the Time library?

Asked

Viewed 2,231 times

1

That is the code:

require 'time'
t  = Time.parse('2016-04-18') #data de ontém
t2 = Time.now #data atual
t3 = t2 - t # subtração das duas variáveis(datas) acima
puts Time.at(t3) #resultado da subtração

In this case the result should be a day and a few hours, but the program returns me that date: "1970-01-02 08:00:42 -0300". I don’t know where I’m going wrong.

1 answer

0


What happens is, by subtracting t - t2, ruby will return a difference float, and when calling Time.at(t3), it will convert that difference into a compatible date. Not exactly, past time.

What you must be looking for could be this:

require 'time'
tempo_atras  = Time.parse('2016-04-18')

agora = Time.now

dias = (     agora.day   -   tempo_atras.day  ).to_s
horas = (    agora.hour  -   tempo_atras.hour ).to_s
minutos = (  agora.min   -   tempo_atras.min  ).to_s
segundos = ( agora.sec   -   tempo_atras.sec  ).to_s
meses = (    agora.mon   -   tempo_atras.mon  ).to_s
anos = (     agora.year  -   tempo_atras.year ).to_s

puts *["dias: "+dias, "horas: "+horas, "minutos: "+minutos, "segundos: "+segundos, "meses: "+meses, "anos: "+anos]
  • Perfect! It was just that!. Thank you very much!

  • @Constantinology I thank for the choice ;)

Browser other questions tagged

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