1

I am writing a Ruby script which uses the mysql2 gem and runs under apache2/passenger.It does not use rails.

The script iterates through a mySql query result and compares a database date to today to get the elapsed time in days. The problem is that the resultant string from subtracting a database date from Date.new is a string like -2457521/1. The correct answer should be 0.

I have tried converting the date to a Ruby date with Date.parse() and Date.strptime() but get the same result. How can I subtract these dates to get the number of days between them?

Here is a redacted code extract from my script.

require 'mysql2'

class Uptime

  def call(env)

    results = con.query("SELECT * FROM Uptimes ORDER BY Up DESC LIMIT 10")

    flag = 0

    results.each(symbolize_keys: true) do |row| 

       if flag == 0 
          last_event = row[:Up]  # => 2016-05-12
          flag = 1
       end

    end  

#        last_event = Date.parse("#{last_event}")

#        last_event = Date.strptime("#{last_event}" "%Y-%m-%d") 

         days = Date.new - last_event # => -2457521/1


        [200, {"Content-Type" => "text/html"}, [html]]
  end
end

1 Answer 1

1

I think your problem is the fact that you are using Date.new when I run Date.new in irb it returns the following:

#<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>

That looks like a 1st January of some year.

If you use Date.today instead that will return the current date to you.

I get this when I run that in irb #<Date: 2016-05-12 ((2457521j,0s,0n),+0s,2299161j)> notice 2016-05-12 vs -4712-01-01 this is also the reason why your result is negative.

Hope this answer helps :)

Sign up to request clarification or add additional context in comments.

4 Comments

That's close but Date.today - last_event returns 0/1
Please can you tell me what is the result of running last_event.class? I notice you have commented out Date.parse("#{last_event}") maybe last_event is not of the Date class when you are subtracting it from Date.today
I have previously checked class and found them to be both Date. Anyway, (Date.today - last_event).to_i gives me the right result so I will mark your answer correct, thanks.
Glad I could help :) and thank you for accepting my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.