Ruby 中的解析时间

Parse Time in Ruby

我正在尝试将此日期 Wed, 17 Feb 2021 13:00:00 +0100 解析为此 2021-02-17 13:00:00.000000000 +0100

我试过使用这个 Time.strptime(current_time.to_s, '%Q'),(其中 current_time 是上面的日期)但我得到 1970-01-01 01:00:02.021 +0100

但我不明白为什么我要再约会一次,你能帮帮我吗?谢谢!

I'm trying to parse this date Wed, 17 Feb 2021 13:00:00 +0100 [...]

您似乎已经有了 Time 的实例:(或 ActiveSupport::TimeWithZone 是 Rails' drop-in 具有更好时区支持的替代品)

current_time = Time.current
#=> Thu, 19 May 2022 10:09:58.702560000 CEST +02:00

在这种情况下,没有什么可以解析。您只需要按照您喜欢的方式 格式化 它:

current_time.strftime('%F %T.%N %z')
#=> "2022-05-19 10:09:58.702560000 +0200"

仅当您有一个要转换为 Time 对象的 字符串表示形式 时才需要解析,例如:(使用 Rails' Time.zone.parse变体)

time_string = 'Thu, 19 May 2022 10:09:58.702560000 CEST +02:00'

time_obj = Time.zone.parse(time_string)
#=> Thu, 19 May 2022 10:09:58.702560000 CEST +02:00

time_obj.class
#=> ActiveSupport::TimeWithZone