1

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.

Nik
  • 2,885
  • 2
  • 25
  • 25
kg.
  • 633
  • 1
  • 5
  • 17

2 Answers2

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Thank you, I missed the iana_timezone property in the API reference – kg. Apr 23 '19 at 20:20
  • @kg. your question is about _parsing_ a given timezone string from an (external) API whereas this answer is about _formatting_ a timezone. How did it solve your parsing problem? – Stefan Apr 24 '19 at 10:13
  • 1
    It was an [XY Problem](https://meta.stackexchange.com/a/66378/201534). How to get a useable time one identifier from the Shopify API was the X. Parsing strings was the Y. – Matt Johnson-Pint Apr 24 '19 at 14:27
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)
Md. Farhan Memon
  • 6,055
  • 2
  • 11
  • 36
  • Thank you, if I cannot find a way to parse the API's Time.zone.to_s back into a Ruby class, then I will go with a string strip solution – kg. Apr 23 '19 at 18:50