How do I change the zone offset for a time in Ruby on Rails?

前端 未结 13 2407
感情败类
感情败类 2020-12-30 22:03

I have a variable foo that contains a time, lets say 4pm today, but the zone offset is wrong, i.e. it is in the wrong time zone. How do I change the time zone?

When

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 22:28

    Option 1

    Use date_time_attribute gem:

    my_date_time = DateTimeAttribute::Container.new(Time.zone.now)
    my_date_time.date_time           # => 2001-02-03 22:00:00 KRAT +0700
    my_date_time.time_zone = 'Moscow'
    my_date_time.date_time           # => 2001-02-03 22:00:00 MSK +0400
    

    Option 2

    If time is used as an attribute, you can use the same date_time_attribute gem:

    class Task
      include DateTimeAttribute
      date_time_attribute :due_at
    end
    
    task = Task.new
    task.due_at_time_zone = 'Moscow'
    task.due_at                      # => Mon, 03 Feb 2013 22:00:00 MSK +04:00
    task.due_at_time_zone = 'London'
    task.due_at                      # => Mon, 03 Feb 2013 22:00:00 GMT +00:00
    

提交回复
热议问题