Traditional methods See: http://www.cnblogs.com/chentianwei/p/9369904.html
?? : Two methods Finally, a similar before_action:set_time_zone in the controller is needed to assign the time zone to the current browser.
Real-time method, according to the user's time zone setting:
- Rails new-m template.rb timezone use template, name with timezone
- yarn Add jstz #一个javascrit TimeZone Library can automatically detect and set the user's time zone.
- Rails g Migration Addtimezonetousers Time_zone
- Rails Db:migrate
- Atom. After opening javascript/packs/application.js (already installed using Webpacker)
- Enter import Jstz from ' Jstz '
- Import Jstz from ' Jstz '
- Const TIMEZONE = Jstz.determine ()
- Console.log (Timezone.name ())
- App/views/shared/_head.html.erb
- Modify line 8th and change to Javascript_pack_tag method.
- On the User registration page, the F.time_zone_select:time_zone option allows you to see the time zone selection on the inspect.
- Set the cookie in Javascript/packs/application.js:
Create a function--set a 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 ()
}
Use this function:
Setcookie ("TimeZone", Timezone.name ())
Parsing these are JavaScript usages, create, Read a Cookie with JavaScript:
var x = Document.cookie The associated cookie for the current document.
Document.cookie = Newcookie sets a new cookie.
Example:
document.cookie= "Username=john Doe; Expires=thu, 12:00:00 UTC; path=/";
Extended--javascript Cookies:
Https://www.w3schools.com/js/js_cookies.asp
12. Define a method in the controller in APPLICATION.RB Bowser_time_zone
def Browser_time_zone
#根据cookies来找到对应的时区, if not, use Time.zone as the default, arbitrary error, and rescue using the default
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方法
The variable Browser_tz is an object such as #<tzinfo::D atatimezone:america/chicago>, which compares the properties TZInfo of all TimeZone objects.
#<activesupport::timezone:0x00007f97f26b0058 @name = "American Samoa", @utc_offset =nil, @tzinfo =#<tzinfo: :D atatimezone:pacific/pago_pago>>
13. On the User registration page, the F.time_zone_select:time_zone option can be added with this browser_time_zone helper method
<%= F.time_zone_select:time_zone, nil, Default:browser_time_zone.name%>
14. The browser displays time zones: Controller adds a before_action:set_time_zone, if:: User_signed_in?
def Set_time_zone
Time.zone = Current_user.time_zone
End
15 has a related gem ' local_time ' available.
(gorails) automatically detects the user's time zone, using JavaScript's Jszt library.