ruby mysql时间戳差异

时间:2017-01-08 15:54:23

标签: mysql ruby

我正在尝试从mysql获取本地时间并使用它来减去ruby时间。

from_db = "2017-01-08 15:51:09"    #this is from mysql database LOCALTIMESTAMP() function

on ruby​​,

local_time = Time.now.utc
local_timestamp = local_time.strftime("%Y-%m-%d %H:%M:%S")    #converting to same format of mysql result
diff_time = local_timestamp - from_db  # trying to subtract 

但它失败并说下面的错误,

irb(main):001:0> from_db = "2017-01-08 15:45:09"
=> "2017-01-08 15:45:09"
irb(main):002:0> local_time = Time.now.utc
=> Sun Jan 08 15:52:45 UTC 2017
irb(main):003:0> local_timestamp = local_time.strftime("%Y-%m-%d %H:%M:%S")
=> "2017-01-08 15:52:45"
irb(main):004:0> diff_time = local_timestamp - from_db
NoMethodError: undefined method `-' for "2017-01-08 15:52:45":String
        from (irb):4
        from :0
irb(main):005:0>

1 个答案:

答案 0 :(得分:1)

您应该从数据库中解析时间,然后使用Time对象而不是字符串进行操作:

require 'time'

from_db = Time.parse("2017-01-08 15:51:09").utc
local_time = Time.now.utc

diff_time = local_timestamp - from_db
=> 11667.904242 #seconds