tech_human
tech_human

Reputation: 7166

Conversion from ISO8601 Duration to Time and from Time to ISO8601 Duration

I have duration value in ISO8601 format and I convert it to the value of time as an integer number of seconds as below:

Duration value in ISO8601 format = "P1Y".

duration = ISO8601::Duration.new(params[:duration]).to_seconds

# duration would have value in float, but I need it in int, so converting it to int.
time_in_seconds = (Time.now - duration).to_i

I store the value in 'time_in_seconds'. So when I retrieve the value would be in int, which I want to convert back to ISO8601 duration format so I should get "P1Y" back after conversion.

Is there a quick way to do this? Or will I have to convert the int value of Time to float and through some method convert it to ISO8601 duration.

Upvotes: 3

Views: 3633

Answers (3)

Andrei
Andrei

Reputation: 625

If you're on Rails then

> time_in_seconds = 7425
=> 7425
> ActiveSupport::Duration.build(time_in_seconds).iso8601
=> "PT2H3M45S"

Upvotes: 2

Artem P
Artem P

Reputation: 5331

There is ActiveSupport::Duration now:

[4] pry(main)> ActiveSupport::Duration.parse('PT5S')
=> 5 seconds
[5] pry(main)> ActiveSupport::Duration.parse('PT5S').to_i
=> 5

Upvotes: 5

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

I would suggest you either to use the ruby-duration gem:

time_in_seconds = 100

require 'ruby-duration'

puts Duration.new(:seconds => time_in_seconds).iso8601
# => PT1M40S

or to take a look at the implementation there and/or steal it.

Upvotes: 3

Related Questions