markhorrocks markhorrocks - 5 months ago 10
SQL Question

Ruby script with mysql2 gem - compare db date to

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 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


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

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

days = - last_event # => -2457521/1

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


I think your problem is the fact that you are using when I run 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 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 :)