Can Ruby Print Out Time Difference (Duration) Readily

Can Ruby print out time difference (duration) readily?

Here's a quick and simple way to implement this. Set predefined measurements for seconds, minutes, hours and days. Then depending on the size of the number, output the appropriate string with the those units. We'll extend Numeric so that you can invoke the method on any numeric class (Fixnum, Bignum, or in your case Float).

class Numeric
def duration
secs = self.to_int
mins = secs / 60
hours = mins / 60
days = hours / 24

if days > 0
"#{days} days and #{hours % 24} hours"
elsif hours > 0
"#{hours} hours and #{mins % 60} minutes"
elsif mins > 0
"#{mins} minutes and #{secs % 60} seconds"
elsif secs >= 0
"#{secs} seconds"
end
end
end

DateTime comparison and math in Ruby

There is a Time library which you can require and then it will extend the default Time class with extra methods, like #parse.

require 'time'
t1 = Time.parse('2015-08-26T12:10:54Z') #trusting the heuristic to match this as ISO8601 type date
t2 = Time.parse('2016-01-05T10:57:02Z')

> t2 - t1
=> 11400368.0 #difference in seconds

As the time is now in seconds, you can easily check for a difference threshold of 45*60. However you have to be very careful to use the same timezone on both date.

You gave an example with Time.now however it will be calculated from your local timezone while the dates you have provided are in UTC (with the "Z" at the end). Subtracting them can give you different result when Daylight Saving is active or inactive in your timezone.

If every date you check against the Time.now is in UTC, you should use Time.now.utc instead.

To calculate a time difference you can use the Time.utc(0) as base.

> Time.utc(0)
=> 0000-01-01 00:00:00 UTC
> Time.utc(0) + 11400368.0
=> 0000-05-11 22:46:08 UTC

You can easily extract the hour:minutes:seconds from here.

How to show time written out?

humantime is one option, but Rails already has time_ago_in_words and distance_of_time_in_words.

Ruby, get hours, seconds and time from Date.day_fraction_to_time

I don't know why it was made private, but you can still access it:

hours,minutes,seconds,frac = Date.send(:day_fraction_to_time, stop-start)

This way you override the OOP encapsulation mechanizm... This is not a very nice thing to do, but it works.

How do I perform timedelta and date comparison in Ruby?

require 'time'

xmas = DateTime.new(2013, 12, 25)
puts x = xmas + 1 # 2013-12-26T00:00:00+00:00
d = DateTime.now
puts x > d # true
puts x - d # 30167183979194791/86400000000000 (a Rational)
puts d >> 12 # 2014-01-10T21:15:20+01:00

How to generate a human readable time range using ruby on rails

If you need something more "precise" than distance_of_time_in_words, you can write something along these lines:

def humanize(secs)
[[60, :seconds], [60, :minutes], [24, :hours], [Float::INFINITY, :days]].map{ |count, name|
if secs > 0
secs, n = secs.divmod(count)

"#{n.to_i} #{name}" unless n.to_i==0
end
}.compact.reverse.join(' ')
end

p humanize 1234
#=>"20 minutes 34 seconds"
p humanize 12345
#=>"3 hours 25 minutes 45 seconds"
p humanize 123456
#=>"1 days 10 hours 17 minutes 36 seconds"
p humanize(Time.now - Time.local(2010,11,5))
#=>"4 days 18 hours 24 minutes 7 seconds"

Oh, one remark on your code:

(self.created_at..self.updated_at).count

is really bad way to get the difference. Use simply:

self.updated_at - self.created_at

Rails: What is the correct way of saving the time of a video?

The way of keeping time depends of you business logic.
I would prefer to keep length in seconds, and then convert to minutes, hours and so on.
You can easily do it by simple devision:

minutes = (seconds / 60)
seconds_left = (seconds % 40)
human_time = "#{minutes}:#{seconds_left}"

Python timedelta and datetime.min in Ruby

The simple equivalent of Python's datetime would be Ruby's Time.

The Time initializer accepts year, month, day, hour, minute, second, offset, so instantiating the earliest possible Time is start_time = Time.new(0).

Time will perform addition in seconds, so you can add 9 hours with start_time + (60 * 60 * 9) or 30 minutes with start_time + (60 * 30).

I'm not sure if Time#strftime is an exact match to Python's, but you can still get 09:00 AM with some_time.strftime('%I:%M %p').



Related Topics



Leave a reply



Submit