检查用户使用的日期格式

时间:2018-09-16 04:26:11

标签: ruby-on-rails ruby

如何在Rails应用程序中检查用户当前使用的默认日期时间格式?

我有这种方法:

def local_date(date, am_pm = false)
  unless am_pm
    date&.localtime&.strftime('(%d.%m.%Y, %H:%M)')
  else
    date&.localtime&.strftime('(%d.%m.%Y, %I:%M %p)')
  end
end

我需要根据用户本地计算机的日期时间格式设置am_pm,而不必依赖:locale参数,因为不是每个会说英语的人都使用am / pm

1 个答案:

答案 0 :(得分:0)

只有在一些客户端JavaScript代码的帮助下,这才能在Rails中实现。客户端代码将检测用户使用的是24小时制还是12小时制,然后存储该cookie信息。

然后,您的服务器端代码应从cookie中读取该信息,并相应地设置您的时间格式。

将此添加到您的app/assets/javascript/application.js文件中。

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}






var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
var dateString = date.toLocaleTimeString();

//apparently toLocaleTimeString() has a bug in Chrome. toString() however returns 12/24 hour formats. If one of two contains AM/PM execute 12 hour coding.
if (dateString.match(/am|pm/i) || date.toString().match(/am|pm/i) )
{
    //12 hour clock

    //check if we are already rendering in 12 hours format
    if(getCookie("time_format") != "twelve") 
    {
       document.cookie = "time_format=twelve";

       /***
         Now force the browser to reload current page from server.
         Since we had set the the cookie, the server will now render 
         all pages in 12 hours format
       ****/

       location.reload(true).

    }
}
else
{
    //24 hour clock
    document.cookie = "time_format=twenty_four";
}

在您的ApplicationController中

class SomeController < ApplicationController
  around_faction :set_time_format

  def set_time_format
    if cookie[:time_format]=="twelve"
      #Set your desired time format string with 12 hour style
    else
      #default
      #Set your desired time format string with 24 hour style
    end
  end

end