带有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 联系我们: