Make Rails ignore daylight saving time when displaying a date

后端 未结 1 939
谎友^
谎友^ 2020-12-16 06:12

I have a date stored in UTC in my Rails app and am trying to display it to a user who has \"Eastern Time (US & Canada)\" as their timezone. The problem is t

相关标签:
1条回答
  • 2020-12-16 06:49

    Create a helper that utilizes the dst? method on TimeZone to check whether the passed timezone is currently in DST. If it is, then subtract an hour from the supplied DateTime instance:

    # helper function
    module TimeConversion
      def no_dst(datetime, timezone)
        Time.zone = timezone
    
        if Time.zone.now.dst?
            return datetime - 1.hour
        end
    
        return datetime
      end
    end
    

    Then, render the adjusted (or non-adjusted) time in your view:

    # in your view
    <%= no_dst(DateTime.parse("2013-08-26T00:00:00Z"), 'Eastern Time (US & Canada)') %>
    #=> Sun, 25 Aug 2013 19:00:00 EDT -04:00
    
    0 讨论(0)
提交回复
热议问题