我有这个字符串:
星期天,10月7日下午4:00
当我使用 Time.parse
时,Ruby 假定时区为 UTC。我如何告诉 Ruby 给我 -0700 时区?我尝试使用
tz.utc_to_local(Time.parse(string))
但我仍然收到UTC +0000时区的时间。
“在解析时间信息时,重要的是永远不要忘记指定时区。”
这个宝贵的建议来自于这篇有用的博客文章:在Ruby on Rails中使用时区。
无论您是否使用Rails,时间字符串始终附带有时区。在您的情况下,您假设时间字符串具有-0700偏移量,但未将时区信息传递给解析方法(该方法假定为UTC)。
> Rails.application.config.time_zone
=> "Mountain Time (US & Canada)"
这是因为我有以下配置:
config.time_zone = 'Mountain Time (US & Canada)'
> string = "Sunday, Oct 7 4:00pm"
=> "Sunday, Oct 7 4:00pm"
> Time.parse(string)
=> 2012-10-07 16:00:00 -0600
> Time.parse(string).zone
=> "MDT"
在纯 Ruby 中也是同样的工作方式:
> require 'time'
=> true
> Time.local( 2012, 10, 07 )
=> 2012-10-07 00:00:00 -0600
> Time.local( 2012, 10, 07 ).zone
=> "MDT"
> string = "Sunday, Oct 7 4:00pm"
=> "Sunday, Oct 7 4:00pm"
> Time.parse(string)
=> 2012-10-07 16:00:00 -0600
> Time.parse(string).zone
=> "MDT"
请确保您的时区设置正确
config.time_zone = 'Eastern Time (US & Canada)'
Time.parse应该默认为当前时区,但您也可以尝试
Time.parse('####').in_time_zone