ruby 将不带时区的时间戳字符串转换为已知时区的Time对象

agyaoht7  于 2023-08-04  发布在  Ruby
关注(0)|答案(3)|浏览(101)

我有一些时间戳字符串(例如“23/06/2021 13:46”),我知道是在英国当地时间(GMT或BST取决于一年中的时间),但它们没有时区指示作为字符串的一部分。
在rails中,什么是将它们转换为正确时区的Time对象的明智方法?
我可以用一种非常迂回的方式来做:

time_string = "23/06/2021 13:46"
base_time = Time.parse(time_string)

Time.use_zone("Europe/London") do
  Time.zone.now.change(year: base_time.year, month: base_time.month, day: base_time.day, hour: base_time.hour, min: base_time.min, sec: base_time.sec)
end

=> Wed, 23 Jun 2021 13:46:00 BST +01:00

字符串
但一定有更好的办法!
我读过很多不同的源代码,似乎都是关于如何将现有的时间对象转换为不同的时区,或者将Time对象转换为字符串。
谢谢你,谢谢

xyhw6mcr

xyhw6mcr1#

您可以使用in_time_zone方法将时间戳转换为服务器的时区:

time_string = "23/06/2021 13:46"
base_time = Time.parse(time_string)
new_time = base_time.in_time_zone

字符串

d4so4syb

d4so4syb2#

我最终使用了一个名为“Time of Day”的gem,它将获取一个字符串并给予你一个时间对象,然后你可以在你选择的任何日期将其转换为当前Time.zone中的本地时间:

Time.zone = "Europe/London"

time_string = "23/06/2021 13:46"
parts = time_string.split(" ")

date = Date.parse(parts[0])
tod = Tod::TimeOfDay.parse(parts[1])

tod.on date   # => Wed, 23 Jun 2021 13:46:00 BST +01:00

字符串

eufgjt7s

eufgjt7s3#

您可以使用Time.find_zone方法。

Time.find_zone("UTC").parse("23/06/2021 13:46")
# => Wed, 23 Jun 2021 13:46:00.000000000 UTC +00:00

字符串
Time.find_zone返回一个ActiveSupport::TimeZone示例,该示例提供了一个parse方法,用于解析该时区的字符串。

相关问题