EastsideDev
EastsideDev

Reputation: 6659

Converting a UTC date string into a localized date string in Ruby or Rails

I have a date, saved as a string:

my_utc_date_str = "2019-09-15T20:42:15"

This is saved as a UTC date string

My local zone, is:

America/Los_Angeles

What I would like to get is:

2019-09-15 13:42:15

Which is that UTC date, localized to USA Pacific Time Zone.

I tried various combinations of DateTime, Time and Date, with no luck. Any ideas bow to do this, without changing the Time Zone for the session?

Upvotes: 0

Views: 426

Answers (1)

max
max

Reputation: 102443

Time.zone.parse("2019-09-15T20:42:15")
    .in_time_zone("America/Los_Angeles")
    .strftime("%Y-%m-%d %H:%M:%S")
# => "2019-09-15 13:42:15"

See ActiveSupport::TimeWithZone for the ActiveSupport extension to Rubys time and date objects and ActiveSupport::TimeZone for a list of time zone mappings.

But for caching reasons you should consider localizing dates and times on the client side.

Upvotes: 2

Related Questions