In Rails, what's the nicest way to create a specific time (not now) in a particular time zone?

后端 未结 5 721
庸人自扰
庸人自扰 2021-02-01 01:36

Here\'s one way, but it\'s can you think of a nicer or more \'railsy\' method?

>> Time.use_zone(\'Sydney\'){ Time.zone.parse(\'2011-04-12 2pm\') }
=> T         


        
相关标签:
5条回答
  • 2021-02-01 02:04

    As said above, to create a time in a specific timezone (e.g., 4/10/2014 1:30pm New York):

    @event.start_time = Time.find_zone('Eastern Time (US & Canada)').local(2014,4,10,13,30)
    => Thu, 10 Apr 2014 13:30:00 EDT -04:00 
    
    @event.start_time.utc
    => 2014-04-10 17:30:00 UTC
    

    When it is saved to your db, it will be converted to UTC (in Postgres at least if using a timestamp type in your migration), and on future access it will be displayed relative to the application timezone set in config/application.rb

    To properly display the local time, we also store the timezone name (e.g., 'Eastern Time (US & Canada)' ) in our database. So, when we want to print the time in our views, we do...

    @event.start_time.in_time_zone(@event.timezone)
     => Thu, 10 Apr 2014 13:30:00 EDT -04:00 
    

    To get the abbreviated timezone (e.g., EST)

    @event.start_time.in_time_zone(@event.timezone).zone
    => "EDT" 
    
    0 讨论(0)
  • 2021-02-01 02:07

    How about using the *in_time_zone* helper..

    Time.now.in_time_zone('Sydney')
    
    0 讨论(0)
  • 2021-02-01 02:11

    This is what I use:

    Time.zone.local(2011, 4, 12, 14, 0)
    
    0 讨论(0)
  • 2021-02-01 02:14

    I think you're looking for

    Time.find_zone('Alaska').local(2011,1,1)
    => Sat, 01 Jan 2011 00:00:00 AKST -09:00
    
    Time.find_zone('Amsterdam').local(2011,1,1)
    => Sat, 01 Jan 2011 00:00:00 CET +01:00 
    
    Time.find_zone('Sydney').local(2011,1,1)
    => Sat, 01 Jan 2011 00:00:00 EST +11:00  
    
    Time.find_zone('Wellington').local(2011,1,1)
    => Sat, 01 Jan 2011 00:00:00 NZDT +13:00
    

    This also works with parse

    Time.find_zone('Sydney').parse('2011-04-12 2pm')
    => Tue, 12 Apr 2011 14:00:00 EST +10:00 
    
    0 讨论(0)
  • 2021-02-01 02:16

    For parsing a date within a specific time zone, you can use ActiveSupport::TimeZone

    > ActiveSupport::TimeZone["Sydney"].parse("2011-04-12 2pm")
    => Tue, 12 Apr 2011 14:00:00 EST 10:00
    

    TimeZone API documentation is here: http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html#method-c-5B-5D

    0 讨论(0)
提交回复
热议问题