Change time formate in rails - ruby-on-rails

I have a Time object which contains minutes and seconds like "05:37". I like to know a way to convert this to the following formate : "5m 37s".

If we are talking of of a Time object, this is easy:
t=Time.now
puts "#{t.min}m #{t.sec}s"
=>15m 28s
If you have a string
s="05:37"
t=s.split(':').map{|i| i.to_i}
puts "#{t.first}m #{t.last}s"
=>5m 37s
Or shorter
s.split(':').map{|i| i.to_i}.join("m ")+"s"

While I agree with the comment suggesting strftime, you could also just use gsub:
"05:37".gsub(/(\d+):(\d+)/, '\1m \2s')
#=> "05m 37s"
If you don't want the leading zero, it's easy enough to get rid of.

[your_time_object].strftime('%Mm %Ss').
For further detail try this

Nevermind got it:
[(total_response_time.to_i / counter_for_response_time.to_i) / 60 % 60, (total_response_time.to_i / counter_for_response_time.to_i) % 60].map { |t| t.to_s.rjust(2,'0') }.join('m ')
For anyone who want to convert it like this in future.

Related

How do I display fractions of a second in my time formatting function?

I'm using Rails 5. I have a method that is supposed to help display a duraiton in milliseconds in a more readable format (hours:minutes:seconds) ...
def time_formatted time_in_ms
regex = /^(0*:?)*0*/
Time.at(time_in_ms/1000).utc.strftime("%H:%M:%S").sub!(regex, '')
end
This works basically fine, but it doesn't work completely accurately when the time in milliseconds contains fractions of a second. That is, if the time in milliseconds is
2486300
The above displays
41:26
but really it should display
41:26.3
How can I adjust my function so it will also display fractions of a second, assuming there are any?
For accuracy make sure you're returning a float (I've used to_f to do this).
Append the argument to strftime with ".%1N" for 1-digit milliseconds.
def time_formatted time_in_ms
regex = /^(0*:?)*0*/
Time.at(time_in_ms.to_f/1000).utc.strftime("%H:%M:%S.%1N").sub!(regex, '')
end
time_formatted 2486300
#=> "41:26.3"
For more information see Time#strftime in the official Ruby documentation.

How to convert X months to Y days in Rails in one step?

I have a configuration value stored as 3.months, and another value returning from a calculation as 7.days.
I need to find their difference. What is the easiest & Railsiest way to normalise them so that I can subtract 7.days from 3.months? I can turn .months into days by using .to_i & multiplying by seconds-in-a-day, but it feels pretty long-winded to have to calculate from months to seconds to days like this:
x = (3.months.to_i/86400).days
=> 90 days
x - 7.days
=> 83 days
Is there a snappier way?
If you want to keep each term with units of time I would recommend this:
(3.months - 7.days)/1.day
I feel like its the cleanest and easiest for another dev to realize what you are trying to describe.
Not sure it's any better but:
end_date = Date.today.advance(months: 3) - 7.days
(end_date - Date.today).to_i #=> 83
I'f I understand correctly, you can subtract them one from another like so:
(3.months - 7.days)/86400 #=> 83
Both months and days methods return an integer of seconds.

Ruby on Rails - YouTube API - How to format duration ISO 8601 (PT45S)

I've searched high and low and can't seem to find a straight answer on this. Basically, I'm calling the YouTube API and getting a JSON document back, then parsing it. Everything else is good, but I don't understand how to parse the 'duration' property to display it as human readable.
The 'duration' field comes over as 'PT1H5M34S' - 1 hour 5 minutes 34 seconds
Or it could be 'PT24S' - 24 seconds
Or 'PT4M3S' - 4 minutes 3 seconds
There has to be a way in Ruby to parse this string and make it human readable so that I can just pass in the duration on the fly in my loop and convert it. Any help or guidance is greatly appreciated. I've tried using Date.parse, Time.parse, Date.strptime, along with many other things... Like just gsub-ing the PT out of the string and displaying it, but that doesn't seem right.
Try arnau's ISO8601 parser (https://github.com/arnau/ISO8601)
Usage:
d = ISO8601::Duration.new('PT1H5M34S')
d.to_seconds # => 3934.0
A simple approach to get the number of seconds for videos less than 24 hours:
dur = "PT34M5S"
pattern = "PT"
pattern += "%HH" if dur.include? "H"
pattern += "%MM" if dur.include? "M"
pattern += "%SS"
DateTime.strptime(dur, pattern).seconds_since_midnight.to_i
You can use Rails ActiveSupport::Duration
parsed_duration = ActiveSupport::Duration.parse(youtube_duration)
Time.at(parsed_duration).utc.strftime('%H:%M:%S')

Set certain size and content to an array

I am developing an Rails 3.2.14 app and in this app I am creating
an array with exactly 31 zeros in it:
<% #total = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] %>
I know there must be a better way to do this right?
Thankful for all input!
Array.new is probably the cleanest way to do this:
Array.new(31, 0)
The first argument is the size, the second is the default value.
Some other alternatives:
[0] * 31
31.times.collect{0}
31.times.inject([]){|array, count| array << 0}
These methods are trivial if you're filling with zeros, but if you are calculating values then they can be quite powerful.
You can use Array#new or Array#fill.
Example:
Array.new(31, 0)
or
[].fill(0, 0..30)
both yields the same result.

Ruby: Math functions for Time Values

How do I add/subtract/etc. time values in Ruby? For example, how would I add the following times?
00:00:59 + 00:01:43 + 00:20:15 = ?
Use ActiveSupport, which has a ton of built-in date extensions.
require 'active_support/core_ext'
t1 = "#{Date.today} 00:00:59".to_time
t2 = "#{Date.today} 00:01:43".to_time
t3 = "#{Date.today} 00:20:15".to_time
t1.since(t2.seconds_since_midnight+t3.seconds_since_midnight)
or, if you don't care about the date, only time:
t1.since(t2.seconds_since_midnight+t3.seconds_since_midnight).strftime("%H:%M:%S")
For a full list, check out http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-date
Kind of ugly, but you could use DateTime.parse(each_interval) & calculate the number of seconds in each. Like this:
require 'date'
def calc_seconds(time_string)
date_time = DateTime.parse(time_string)
hour_part = date_time.hour * 60 * 60
minute_part = date_time.minute * 60
second_part = date_time.second
hour_part + minute_part + second_part
end
...which gives you your result in seconds, assuming valid inputs. At which point you can add them together.
You could reverse the process to get the interval in your original notation.
I really think there ought to be an easier method, but I don't know of one.
One way would be to convert everything to seconds and then performing the operations... Then you would need to convert it again to a time object with
Time.at(seconds_result).strftime('%H:%M:%S')
And you would get the time nicely formatted (as a string).
I am trying to find a gem that does this, and other operations.
You probably want to use a gem that does not concern itself with the actual day. You could perform acrobatics using DateTime and or Time, but you would constantly be battling how to handle days.
One gem that may be useful is tod (TimeOfDay), https://github.com/JackC/tod
With that you could directly do TimeOfDay.parse "00:01:43", add the values, and print the result using strftime("%H:%M:%S").

Resources