Rails jQuery Datepicker时区 [英] Rails jquery datepicker timezones

查看:82
本文介绍了Rails jQuery Datepicker时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用Rails处理JQuery日期/时间选择器中的时区时遇到问题.日期选择器正确显示了本地时区.出现问题时,当我将选定的日期保存到数据库中时,Rails会将其保存为UTC时间,即使该时间在客户端的时区中也是如此.当我尝试将时间转换为utc(Time.zone.parse(params [:time]).utc)时,它给了我与params [:time]相同的值,这是本地时间.

I am having an issue trying to deal with timezones in the JQuery date/time picker, with Rails. The datepicker, correctly shows the local timezone. The problem arises, when I save the selected date into my database, rails is saving it as a UTC time, even though the time is in the timezone of the client. When I attempt to convert the time to utc (Time.zone.parse(params[:time]).utc ), it gives me the same value as params[:time], which is the local time.

我也不想在environment.rb文件中更改config.time_zone的设置,因为我也不想将时间保存在服务器的本地时区中.

I do not want to change the Setting of config.time_zone in the environment.rb file, as I do not want the time to be saved in the local timezone of the server either.

我想做的是接收本地时间,并将其转换为utc,因此我可以在时间设置为utc的服务器上安排cron作业.我想将时间保存为数据库中的时间,作为用户的本地时区...但是我无法找到获取客户端时区的方法!

What I want to do, is receive the local time, and convert it to utc, so I can schedule a cron job on a server whose time is set to utc. I would like to save the time in the database, as the users' local timezone... but I am unable to find a way to get the client's timezone!

除了在选择器上添加时区作为选项之外,我还有其他选择吗?

Do I have any other options.. besides adding the timezone as an option on the datepicker?

推荐答案

DateTime Picker为您的视图提供用户正确的时间-在此之后,您可以解析时间,调整用户的时区,并通过增加或减少适当的时间来安排您的cron作业.这是我的处理方法:

DateTime Picker gives your views the correct time for the user - after that it is up to you to parse the time, adjust for the users' time zone, and schedule your cron job accordingly by adding or subtracting the appropriate amount of hours. Here's how I went about it:

# 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帖子中的相关信息将UTC转换为Rails中的本地时间3 :

relavent info from another SO post 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)")

这篇关于Rails jQuery Datepicker时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆