How to Parse Days/Hours/Minutes/Seconds in Ruby

How to parse days/hours/minutes/seconds in ruby?

Posting a 2nd answer, as chronic (which my original answer suggested) doesn't give you timespans but timestamps.

Here's my go on a parser.

class TimeParser
TOKENS = {
"m" => (60),
"h" => (60 * 60),
"d" => (60 * 60 * 24)
}

attr_reader :time

def initialize(input)
@input = input
@time = 0
parse
end

def parse
@input.scan(/(\d+)(\w)/).each do |amount, measure|
@time += amount.to_i * TOKENS[measure]
end
end
end

The strategy is fairly simple. Split "5h" into ["5", "h"], define how many seconds "h" represents (TOKENS), and add that amount to @time.

TimeParser.new("1m").time
# => 60

TimeParser.new("1m wtf lol").time
# => 60

TimeParser.new("4h 30m").time
# => 16200

TimeParser.new("1d 4h").time
# => 100800

It shouldn't be too hard making it handle "1.5h" either, seeing the codebase is as simple as it is.

How to parse time field into hours, minutes and seconds?

If you just want to split time to three separate inputs you can use the time_select helper.

Otherwise use the strftime method; Check http://strfti.me for more help.

Convert duration to hours:minutes:seconds (or similar) in Rails 3 or Ruby

See: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html

distance_of_time_in_words(3600)
=> "about 1 hour"

how to convert 270921sec into days + hours + minutes + sec ? (ruby)

It can be done pretty concisely using divmod:

t = 270921
mm, ss = t.divmod(60) #=> [4515, 21]
hh, mm = mm.divmod(60) #=> [75, 15]
dd, hh = hh.divmod(24) #=> [3, 3]
puts "%d days, %d hours, %d minutes and %d seconds" % [dd, hh, mm, ss]
#=> 3 days, 3 hours, 15 minutes and 21 seconds

You could probably DRY it further by getting creative with collect, or maybe inject, but when the core logic is three lines it may be overkill.

Converting hours, minutes and seconds to seconds in ruby

'12:34:56'.split(':').map(&:to_i).inject(0) { |a, b| a * 60 + b }
=> 45296

Converting seconds into hours only using Ruby in-built function - except the days

Now that I see what you're looking for, I offer this:

def seconds_to_hms(sec)
[sec / 3600, sec / 60 % 60, sec % 60].map{|t| t.to_s.rjust(2,'0')}.join(':')
end

Edit: Another option, even more concise:

def seconds_to_hms(sec)
"%02d:%02d:%02d" % [sec / 3600, sec / 60 % 60, sec % 60]
end

Sample output;

seconds_to_hms(164580)
=> "45:43:00"

Parsing a string into a DateTime object and adding minutes in Ruby

You are adding 1800 days to your date.

I tried this:

text_next = DateTime.strptime(text_t, '%I:%M %p %Z')
puts text_next
text_next = text_next + Rational(30, 1440)
puts text_next

1440 is the amount of minutes in a day.



Related Topics



Leave a reply



Submit