Last active
September 27, 2019 12:53
-
-
Save pachacamac/b8af92eabd2f55444ca3ad539657529d to your computer and use it in GitHub Desktop.
human readable time differences without dependencies
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
def td_in_words(s, skip: 1) | |
words = [['years',0], ['months',1], ['days',1], ['hours',0], ['minutes',0], ['seconds',0]] | |
vals = (Time.mktime(0)+s).strftime("%Y %m %d %H %M %S").split(' ').map(&:to_i) | |
skip.times{ words.pop && vals.pop } | |
str = vals.zip(words).select{|v,(w,n)| v!=n}.map{|v,(w,n)| [v-n, (v-n)==1 ? w[0..-2] : w]}.map{|v,w| "#{v} #{w}"}.join(' ') | |
str = "0 #{words.last[0]}" if str.empty? | |
str | |
end | |
#usage: | |
some_time_in_the_past = Time.now - 12345 * 6789 | |
some_time_in_the_future = Time.now + 654 * 321 | |
puts td_in_words(Time.now - some_other_time) + ' ago' | |
puts td_in_words(some_time_in_the_future - Time.now) + ' from now' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment