帶有mysql2 gem的Ruby腳本 - 將db date與Date.new進行比較

[英]Ruby script with mysql2 gem - compare db date to Date.new


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

我正在編寫一個使用mysql2 gem的Ruby腳本,並在apache2 / passenger下運行。它不使用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.

該腳本遍歷mySql查詢結果,並將數據庫日期與今天進行比較,以獲得以天為單位的經過時間。問題是從Date.new中減去數據庫日期的結果字符串是-2457521/1之類的字符串。正確答案應為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?

我嘗試使用Date.parse()和Date.strptime()將日期轉換為Ruby日期,但得到相同的結果。如何減去這些日期以獲得它們之間的天數?

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 个解决方案

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

我認為您的問題是,當我在irb中運行Date.new時,您正在使用Date.new,它返回以下內容:

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

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

That looks like a 1st January of some year.

這看起來像某一年的1月1日。

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

如果您使用Date.today而將返回當前日期。

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.

當我在irb中運行時我得到這個# <日期:2016-05-12((2457521j,0s,0n),+ 0s,2299161j)> 通知2016-05-12 vs -4712-01-01這也是你的結果是否定的原因。

Hope this answer helps :)

希望這個答案有幫助:)


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/05/12/af63fc2cefb01ba596a1adda7316ae44.html



 
  © 2014-2022 ITdaan.com 联系我们: