developer tip

Rails : UTC DateTime을 다른 시간대로 변환

optionbox 2020. 8. 7. 08:19
반응형

Rails : UTC DateTime을 다른 시간대로 변환


Ruby / Rails에서 UTC DateTime을 다른 시간대로 어떻게 변환합니까?


time.in_time_zone(time_zone)

예:

zone = ActiveSupport::TimeZone.new("Central Time (US & Canada)")
Time.now.in_time_zone(zone)

아니면 그냥

Time.now.in_time_zone("Central Time (US & Canada)")

다음을 수행하여 ActiveSupport 시간대의 이름을 찾을 수 있습니다.

ActiveSupport::TimeZone.all.map(&:name)
# or for just US
ActiveSupport::TimeZone.us_zones.map(&:name)

경우 Time.zone가 원하는 시간대의 당신은 사용할 수 있습니다@date.to_time.to_datetime

> @date
=> Tue, 02 Sep 2014 23:59:59 +0000
> @date.class
=> DateTime
> @date.to_time
=> 2014-09-02 12:59:59 -1100
> @date.to_time.to_datetime
=> Tue, 02 Sep 2014 12:59:59 -1100 

TimeZone으로 조작 된 ActiveSupport의 TimeWithZone 개체를 사용해보십시오 . ActiveSupport는 UTC 시간을 지정된 TimeZone 시간대로 변환하기위한 in_time_zone 메소드도 제공합니다. mckeed의 답변은 코드를 보여줍니다.


Rails에서 ActiveRecord 객체를 다루는 경우를 대비하여.

Time.use_zone설정된 기본 시간대를 재정의하는 요청 당 기준 시간대 를 사용하는 것이 좋습니다 .config.time_zone

자세한 내용은 https://stackoverflow.com/a/25055692/542995 에서 설명합니다.


일반 루비에서는 만 require 'date'사용하여 다음 new_offset방법을 사용하십시오 .

require 'date'

d=DateTime.parse('2000-01-01 12:00 +0200')
l=d.new_offset('-0700')
u=l.new_offset('UTC')
puts "#{u.strftime('%a %F %T %Z')} ❖ #{l.strftime('%a %F %T %Z')}"

Mac OS X 10.13에서 표준으로 제공되는 루비 2.3.7로 테스트되었습니다.


Rails 4에서 simple_form을 사용하고 있으며 입력 필드를 다음과 같이 추가했습니다.

<%= f.input :time_zone, :as => :time_zone %>

마이그레이션과 함께

class AddTimeZoneColumnToTextmessage < ActiveRecord::Migration
  def change
    add_column :textmessages, :time_zone, :string
  end
end

참고 URL : https://stackoverflow.com/questions/2695837/rails-convert-utc-datetime-to-another-time-zone

반응형