(GoRails) 自動偵測用戶的時區,使用javascript 的jszt庫。
傳統方法見:http://www.cnblogs.com/chentianwei/p/9369904.html
??: 兩個方法最後都要有controller中的類似before_action :set_time_zone來給當前瀏覽器分配時區。
實時方法,根據user的時區設置:
- rails new -m template.rb timezone 使用模版,名字用timezone
- yarn add jstz #一個javascrit timezone library 可以自動偵測和設置用戶的time zone。
- rails g migration AddTimeZoneToUsers time_zone
- rails db:migrate
- atom.後打開javascript/packs/application.js(已經安裝使用webpacker)
- 輸入import jstz from ‘jstz‘
- import jstz from ‘jstz‘
- const timezone = jstz.determine()
- console.log(timezone.name())
- app/views/shared/_head.html.erb
- 修改第8行,改為 javascript_pack_tag方法。
- 在user註冊頁,f.time_zone_select :time_zone選項,通過它可以在inspect上看到時區的選擇。
- 在javascript/packs/application.js設置cookie:
創建函數--設置一個Cookie:
function setCookie(name, value) {
var expires = new Date()
expires.setTime(expires.getTime() + (24*60*60*1000)) #1000天後到期
document.cookie = name + ‘‘=" + value + ‘;expires=‘ + expires.toUTCString()
}
使用這個函數:
setCookie("timezone", timezone.name())
解析這些都是JavaScript的用法,create, Read a Cookie with JavaScript:
var x = document.cookie 獲得當前document的關聯的cookies。
document.cookie = newCookie 設置新的Cookie。
例子:
document.cookie= "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";擴展--JavaScript Cookies:
https://www.w3schools.com/js/js_cookies.asp
12. 在Application.rb中 Controller中定義一個方法 bowser_time_zone
def browser_time_zone
#根據cookies來找到對應的時區,如果沒有則使用Time.zone作為默認,任意錯誤,營救也使用默認
browser_tz = ActiveSupport::TimeZone.find_tzinfo(cookies[:timezone])
ActiveSupport::TimeZone.all.find{ |zone| zone.tzinfo == browser_tz } || Time.zone
rescue TZInfo::UnknownTimezone, TZInfo::InvalidTimezoneIdentifier
Time.zone
end
helper_method :browser_time_zone #添加helper方法
變量browser_tz是如#<TZInfo::DataTimezone: America/Chicago>的對象, 它會和所有TimeZone對象的屬性tzinfo做比較。
#<ActiveSupport::TimeZone:0x00007f97f26b0058 @name="American Samoa", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: Pacific/Pago_Pago>>
13.在user註冊頁,f.time_zone_select :time_zone選項可以加上這個browser_time_zone helper方法
<%= f.time_zone_select :time_zone, nil, default: browser_time_zone.name %>
14. 瀏覽器顯示時區時間:controller增加一個before_action :set_time_zone, if: :user_signed_in?
def set_time_zone
Time.zone = current_user.time_zone
end
15 有一個相關gem ‘local_time‘可以利用。
(GoRails) 自動偵測用戶的時區,使用javascript 的jszt庫。