Rares R
Rares R

Reputation: 229

Parsing a date string in Ruby

Currently I'm implementing a feature and using an external API. The API returns the following structure

{"StartDate"=>"/Date(1532563200000+0000)/", "ExpirationDate"=>"/Date(1564099200000+0000)/"}

I'm not sure how to parse StartDate and ExpirationDate to get their values in Ruby Time Format.

Any feedback welcome.

Upvotes: 0

Views: 199

Answers (2)

iGian
iGian

Reputation: 11183

Another of many way for Ruby in general

require 'date'
response.transform_values! { |date| Time.at(date[6..15].to_i).utc.to_datetime }

For Ruby versions not supporting transform_values:

response.inject({}) { |h, (k, v)| h[k] = Time.at(v[6..15].to_i).utc.to_datetime; h }

Thanks to: https://stackoverflow.com/a/812551

Upvotes: 0

AbM
AbM

Reputation: 7779

You can use Time.zone.at to parse a timestamp in seconds.

response = {"StartDate"=>"/Date(1532563200000+0000)/", "ExpirationDate"=>"/Date(1564099200000+0000)/"}

start_date = Time.zone.at(response['StartDate'][6..15].to_i)
#=> Wed, 25 Jul 2018 20:00:00 EDT -04:00

expiration_date = Time.zone.at(response['ExpirationDate'][6..15].to_i)
#=> Thu, 25 Jul 2019 20:00:00 EDT -04:00

Upvotes: 2

Related Questions