【问题标题】:Rails jquery datepicker timezonesRails jquery datepicker时区
【发布时间】:2012-04-02 02:28:46
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: jquery ruby-on-rails timezone datepicker


    【解决方案1】:

    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 帖子 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)")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多