developer tip

Rails에서 한 시간대에서 다른 시간대로 시간 변환

optionbox 2020. 8. 16. 20:10
반응형

Rails에서 한 시간대에서 다른 시간대로 시간 변환


created_at타임 스탬프는 UTC로 저장됩니다.

>> Annotation.last.created_at
=> Sat, 29 Aug 2009 23:30:09 UTC +00:00

그중 하나를 '동부 표준시 (미국 및 캐나다)'로 변환하려면 어떻게해야합니까 (일광 절약 제 고려)? 다음과 같은 것 :

Annotation.last.created_at.in_eastern_time

DateTime 클래스의 in_time_zone 메서드 사용

Loading development environment (Rails 2.3.2)
>> now = DateTime.now.utc
=> Sun, 06 Sep 2009 22:27:45 +0000
>> now.in_time_zone('Eastern Time (US & Canada)')
=> Sun, 06 Sep 2009 18:27:45 EDT -04:00
>> quit

따라서 귀하의 특정 예를 들어

Annotation.last.created_at.in_time_zone('Eastern Time (US & Canada)')

이것은 오래된 질문이지만 언급 할 가치가 있습니다. A의 이전 응답 이 일시적으로 시간대를 설정하는 before_filter를 사용하도록 제안합니다.

Time.zone이 정보를 스레드에 저장하고 해당 스레드가 처리하는 다음 요청으로 누출 될 수 있으므로 절대 그렇게 해서는 안됩니다 .

대신 around_filter를 사용하여 요청이 완료된 후 Time.zone이 재설정되었는지 확인해야합니다. 다음과 같은 것 :

around_filter :set_time_zone

private

def set_time_zone
  old_time_zone = Time.zone
  Time.zone = current_user.time_zone if logged_in?
  yield
ensure
  Time.zone = old_time_zone
end

여기 에 대해 자세히 알아보십시오.


이것을 추가하면 /config/application.rb

config.time_zone = 'Eastern Time (US & Canada)'

그런 다음 세포를

Annotation.last.created_at.in_time_zone

지정된 시간대의 시간을 가져옵니다.


시간대를 동부 표준시로 설정하십시오.

config / environment.rb에서 기본 시간대를 설정할 수 있습니다.

config.time_zone = "Eastern Time (US & Canada)"

이제 꺼내는 모든 레코드가 해당 시간대에 있습니다. 다른 시간대가 필요한 경우 사용자 시간대에 따라 컨트롤러의 before_filter를 사용하여 변경할 수 있습니다.

class ApplicationController < ActionController::Base

  before_filter :set_timezone

  def set_timezone
    Time.zone = current_user.time_zone
  end
end

모든 시간을 데이터베이스에 UTC로 저장하고 있는지 확인하면 모든 것이 멋질 것입니다.


구성하는 경우 /config/application.rb

config.time_zone = 'Eastern Time (US & Canada)'

Time.now.in_time_zone

DateTime.now.in_time_zone

참고 URL : https://stackoverflow.com/questions/1386871/convert-time-from-one-time-zone-to-another-in-rails

반응형