【问题标题】:How can I display local time for data in Rails PostgreSQL correctly如何正确显示 Rails PostgreSQL 中数据的本地时间
【发布时间】:2022-01-28 17:44:59
【问题描述】:

正确的意思是如果活动是太平洋时间 1 月 24 日 上午 9 点,我希望看到 1 月 24 日 上午 9 点,而不是 1 月 24 日下午 5 点。我在 PostgreSQL 数据库中的 Rails 中记录带有时间和日期的事件。带有时区的时间戳 (timestampz)。只要我将计算机上的数据库和应用程序保持在“美国/太平洋”,一切都很好,但是当我尝试从似乎是 UTC 的 Heroku 服务器上使用它时,时间会偏移 8 小时。我现在终于知道 timestampz 只意味着这是 UTC 的日期时间,但没有存储该区域。我是否需要将时区存储在另一个字段中并进行数学运算以正确查看时间和日期?

config.time_zone = "America/Los_Angeles""UTC" 添加到config/application.rb 得到与以前相同的结果,即此设置没有任何区别。这不是最终的解决方案,因为数据并不总是在美国/太平洋地区。

在表格中查看:

<%= stat.statdate.localtime.strftime("%a %d %b %Y") %></td> <td class="text-start"> <%= stat.statdate.localtime.strftime("%_l:%M %P") %>

这会导致本地主机上的Thu 27 Jan 2022 9:05 am,但Heroku上的Thu 27 Jan 2022 5:05 pm

并随着时间的推移绘制价值图表,包括一年和每天。用于绘制最近一天的变化。试图让表格和图表同时工作非常痛苦

其中line_chart 使用gem "chartkick",它使用高图表。但是当我将应用程序和数据库移动到 Heroku 时,这不起作用

【问题讨论】:

    标签: ruby-on-rails postgresql heroku timestamp chartkick


    【解决方案1】:

    我最终是“手动”完成的。获取从数据中提取的时区

    <% last_record = BP.order('statdate asc').last.statdate %><br> # last data point. 
    <% last_record_zone = BP.order('statdate asc').last.statzone  %> # time zone grabbed from statdate in timestampz (so zone was added)
    <% last_record_zone_in_seconds = last_record_zone*3600 %>
    # Getting midnight for the day of the last record in UTC but shifted by the local time of the last record
    <% last_record_midnight = last_record + last_record_zone_in_seconds - (last_record.min*60) - (last_record.sec) %>
    
    # Setting variables used to title the graphs and set beginning and end of daily graphs (set for one week, not shown)
    # The first day is a special case and not shown here
    #
    # For graph title
    <% last_record_1_day_ago = last_record-1.day %>
    <% last_record_2_day_ago = last_record-2.day %>
    #  For daily graph data
    <% span10 = last_record_midnight-1.day..last_record_midnight-0.day %>
    

    除了本地主机和当前服务器之外,没有检查过。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2011-08-16
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多