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

江枫思渺然 提交于 2019-12-11 02:54:24

问题


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.


回答1:


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.




回答2:


There is ActiveSupport::Duration now:

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


来源:https://stackoverflow.com/questions/23556973/conversion-from-iso8601-duration-to-time-and-from-time-to-iso8601-duration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!