我在尝试使用 Rails 处理 JQuery 日期/时间选择器中的时区时遇到问题。日期选择器正确显示当地时区。问题出现了,当我将所选日期保存到数据库中时,rails 会将其保存为 UTC 时间,即使该时间位于客户端的时区中。当我尝试将时间转换为 utc (Time.zone.parse(params[:time]).utc ) 时,它给出与 params[:time] 相同的值,即当地时间。
我不想更改environment.rb文件中config.time_zone的设置,因为我也不希望将时间保存在服务器的本地时区中。
我想要做的是接收本地时间,并将其转换为 utc,这样我就可以在时间设置为 utc 的服务器上安排 cron 作业。我想将时间保存在数据库中,作为用户的本地时区......但我无法找到获取客户端时区的方法!
除了将时区添加为日期选择器上的选项之外,我还有其他选择吗?
DateTime Picker 为您的视图提供了用户的正确时间 - 之后由您来解析时间、调整用户的时区,并通过添加或减去适当的小时数来相应地安排您的 cron 作业。我是这样做的:
# convert your param from a datepicker string to time:
start_time=DateTime.strptime(params[:start_time], "%m/%d/%Y %H:%M:%S").to_time
# datepicker gives times in UTC to your server *BUT* it appears in the local time to the user. Make sure to adjust for this time difference.
start_time = start_time.in_time_zone(current_user.time_zone) # I let users pick their time zone.
# account for DST. does this work? I think so.
offset = (start_time.utc_offset)/60/60
# now adjust by the hours offset. you likely want to keep the time in utc for your database...
adjusted_start_time = (start_time-offset.hours).utc
来自另一个 SO 帖子的相关信息在 Rails 3 中将 UTC 转换为本地时间 https://stackoverflow.com/questions/5300493/convert-utc-to-local-time-in-rails-3:
# Rails has it's own names. See them with: rake time:zones:us To see other zone-related rake tasks: rake -D time
# So, to convert to EST, catering for DST automatically:
Time.now.in_time_zone("Eastern Time (US & Canada)")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)