Rails gives wrong time with strftime across DST border

I have a String "3:30 PM 2014-03-15 Eastern Time (US & Canada)"that I want to convert to a DateTime and store in my database.

It is pretty simple:

str = "3:30 PM 2014-03-15 Eastern Time (US & Canada)"
event.starts_at = DateTime.strptime(str, "%l:%M %p %Y-%m-%d %Z")

This creates a DateTime with the correct time zone. However, if I save the event in the database and then read it like this:

e.starts_at.in_time_zone("Eastern Time (US & Canada)")
    .strftime("%l:%M %p") => #outputs 4:30 PM, when I want it to say 3:30 PM

The result gives the wrong time (it seems because it is configured for DST)! What can I do to fix this problem?

+4
source share
1 answer

DateTime.strptimeis owned by Ruby, and timezone identifiers such as Eastern Time (USA and Canada) are only provided by Rails through ActiveSupport :: TimeZone .

, DateTime . DateTime, %z %z :

Time zone:
    %z - Time zone as hour and minute offset from UTC (e.g. +0900)
            %:z - hour and minute offset from UTC with a colon (e.g. +09:00)
            %::z - hour, minute and second offset from UTC (e.g. +09:00:00)
            %:::z - hour, minute and second offset from UTC
                                              (e.g. +09, +09:30, +09:30:30)
    %Z - Time zone abbreviation name or something similar information.

%z , %z . , . , "EST" "EDT", , , , "". , , , Rails ( - . wiki- ).

, , , - , , . , - , , "" EST. -5 . Rails " ( )", , EDT , -4. - , .

№ 1 - Rails. Ruby TZInfo gem, IANA ids America/New_York.

# 2 - Rails, Time.zone.parse Rails DateTime.strptime.

( Ruby, . , - , , .)

+3

Source: https://habr.com/ru/post/1529698/


All Articles