Amazon Affiliate

Monday 11 April 2016

Convert and print the 12-hour format time to 24-hour format in ruby.

# Input Format

# A single string containing a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01≤hh≤12.

# Output Format

# Convert and print the given time in 24-hour format, where 00≤hh≤23.

puts "Enter the time in 12-hour clock format :"
time = gets.strip
a = time.split(":")
if a[-1].gsub(/[^A-Za-z]/,"") == "PM" || a[-1].gsub(/[^A-Za-z]/,"") == "pm"
    a[0] = (12 + a[0].to_i).to_s
    a[-1] = a[-1].gsub(/[^0-9]/,"")
elsif a[-1].gsub(/[^A-Za-z]/,"") == "AM" || a[-1].gsub(/[^A-Za-z]/,"") == "am"
    a[-1] = a[-1].gsub(/[^0-9]/,"")   
end   
puts a.join(":")

No comments:

Post a Comment