skip to Main Content

I did find this question but I am still stumbling around looking for a simple solution to the following:

An API call returns the following format which looks like they are using Time.zone.to_s

irb> ShopifyAPI::Shop.current.timezone
=> "(GMT-08:00) Pacific Time (US & Canada)"

I would like to parse the "(GMT-08:00) Pacific Time (US & Canada)" into a Ruby class and output the TimeZone name "Pacific Time (US & Canada)"

Alternately I could just strip the "(GMT-08:00)" offset and be left with a clean TimeZone name "Pacific Time (US & Canada)" but this seems like a messy string editing solution.

2

Answers


  1. If you are confident about the API and string format you are going to receive, you can manipulate string as

    string.partition(')').last.strip
    # => Pacific Time (US & Canada)
    
    Login or Signup to reply.
  2. ShopifyAPI::Shop.current returns properties documented here. Yes, timezone is one of them, but it is intended to be a display name, not something you should parse.

    Instead, use the iana_timezone property, which will give you the IANA time zone identifier, such as America/Los_Angeles. These are compatible with Rails, as well as Ruby’s tzinfo gem, and also are used in many other platforms.

    irb> ShopifyAPI::Shop.current.timezone
    => "(GMT-08:00) Pacific Time (US & Canada)"
    
    irb> ShopifyAPI::Shop.current.iana_timezone
    => "America/Los_Angeles"
    

    If you want to get a Rails time zone from there, you can use the MAPPING constant defined in ActiveSupport::TimeZone. Though I’d avoid it if possible, for the reasons mentioned in the timezone tag wiki in the “Rails Time Zone Identifiers” section at the bottom.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search