【问题标题】:How to show user timezone in Rails 4 app?如何在 Rails 4 应用程序中显示用户时区?
【发布时间】:2015-01-06 08:46:45
【问题描述】:

我想显示访问用户的时间和相应的区域。例如,如果在格林威治标准时间中午 12 点创建记录。如果有人在GMT+5 时区访问,则应显示下午 5:00。是否可以在 Rails 中本地实现?我设置了config.active_record.default_timezone = :local,但它在UTC中显示信息

运行rake timezones:local返回多个条目:

* UTC +05:00 *
Ekaterinburg
Islamabad
Karachi
Tashkent

我属于Karachi

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-4 timezone


【解决方案1】:

我不确定这是否可以仅使用 Ruby on Rails 来完成。我不得不使用 JavaScript 将相应的时间更改为客户端的本地时区,在我看来,这不能通过服务器端代码来完成。这就是我在实施中所做的 -

首先创建一个辅助方法:

def show_created_time(record)
  time = record.created_at.strftime('%Y-%m-%dT%H:%M:%S')
  content_tag(:span, time, "data-timer" => time, :class => 'record_created_time')
end

注意:创建这样的辅助方法并不是必须的。您可以只创建一个 HTML 元素(span、p、div 等),它具有data-timer 属性,其时间格式如上所述。

然后调用辅助方法:

<%= show_created_time(record) %>

现在创建一个 JavaScript 文件,例如我们称之为 timer.js:

$(document).ready(function() {
  $("[data-timer]").each(function() {
    var cTime = $(this).attr('data-timer');
    // createdTime for record in db:
    var createdTime = new Date(cTime);
    // Return the timezone difference between UTC and User Local Time
    // var date = new Date();
    var userTimeZoneDiff = createdTime.getTimezoneOffset();
    // Since there are 60,000 milliseconds in a minute
    var MS_PER_MINUTE = 60000;
    // Record final created_at will depend on the final subtracted date as:
    var recordCreatedDateTime = new Date(createdTime - userTimeZoneDiff * MS_PER_MINUTE);

    $(this).text(recordCreatedDateTime);
  });
});

确保在 application.js 中包含这个 js:

//= require timer.js

这是the project 我实现它的地方。在此处添加作为参考。

【讨论】:

    猜你喜欢
    • 2016-08-11
    • 2016-04-15
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 2015-06-27
    相关资源
    最近更新 更多