Created
August 4, 2016 16:43
-
-
Save leonardofaria/ff25202097f25ebcd1aff8ad9c488b43 to your computer and use it in GitHub Desktop.
Time Calculation using Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require_relative './time_calculation.rb' | |
distance = Time.new - Time.parse('2016-1-1') | |
puts TimeCalculation.humanize(distance)+"\r" | |
Date_of_birth = '1888-2-15' | |
3.times do | |
distance = Time.new - Time.parse(Date_of_birth) | |
puts TimeCalculation.humanize(distance, false)+"\r" | |
sleep 1 | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'time' | |
class TimeCalculation | |
def self.pluralize(count, noun) | |
if count != 0 | |
count == 1 ? "#{count.to_i} #{noun}" : "#{count.to_i} #{noun}s" | |
end | |
end | |
def self.humanize(secs, short = true) | |
output = [ | |
[60, :second], | |
[60, :minute], | |
[24, :hour], | |
[365, :day], | |
[100, :year] | |
].map do |count, name| | |
if secs > 0 | |
secs, n = secs.divmod(count) | |
pluralize(n, name) | |
end | |
end | |
if short | |
output.compact.reverse[0] | |
else | |
output.compact.reverse.join(' ') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Initially based on: https://coderwall.com/p/fdlfia/calculate-your-age-in-years-days-hours-minutes-seconds-in-ruby
It doesn't solve 100% of cases. For better results: https://github.com/radar/dotiw