gpt4 book ai didi

mysql - ruby mysql 时间戳差异

转载 作者:行者123 更新时间:2023-11-29 11:05:06 27 4
gpt4 key购买 nike

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

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

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

最佳答案

您应该从数据库中解析时间,然后使用 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

关于mysql - ruby mysql 时间戳差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41534576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com