Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby ISO 8601 duration converter
require 'test/unit'
# implementation
class Duration
def in_seconds(raw_duration)
match = raw_duration.match(/PT(?:([0-9]*)H)*(?:([0-9]*)M)*(?:([0-9.]*)S)*/)
hours = match[1].to_i
minutes = match[2].to_i
seconds = match[3].to_f
seconds + (60 * minutes) + (60 * 60 * hours)
end
end
# tests
class TestDuration < Test::Unit::TestCase
def setup
@duration = Duration.new
end
def test_just_seconds_with_decimal
assert @duration.in_seconds('PT23.162S') == 23.162
end
def test_just_seconds_without_decimal
assert @duration.in_seconds('PT23S') == 23
end
def test_minutes_and_seconds_with_decimal
assert @duration.in_seconds('PT2M4.123S') == 124.123
end
def test_minutes_and_seconds_without_decimal
assert @duration.in_seconds('PT2M4S') == 124
end
def test_hours_minutes_and_seconds_with_decimal
assert @duration.in_seconds('PT1H2M4.7S') == 3724.7
end
def test_hours_minutes_and_seconds_without_decimal
assert @duration.in_seconds('PT1H2M4S') == 3724
end
def test_hours_seconds_no_minutes
assert @duration.in_seconds('PT1H6S') == 3606
end
def test_hours_minutes_no_seconds
assert @duration.in_seconds('PT1H1M') == 3660
end
def test_just_hours
assert @duration.in_seconds('PT4H') == 14_400
end
def test_hours_and_seconds
assert @duration.in_seconds('PT4H1.04S') == 14_401.04
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment