Ruby: Simple Calculation of Billable Time using Epoch-Seconds

How to calculate billable time in Ruby using epoch-seconds. Out of interest,I ported the Perl-Code to Ruby and have to say, wow. Ruby is very elegant (not sure if my code is, but it works).

The idea was to use another (scripting-)language readily available on OS X. As I said already, it works like the Perl-version:


#!/usr/bin/ruby

# Variables
starttime = Time.now
epochtime = starttime.to_i

# write to file
timetemp = File.new("timetemp.txt", "w+")

timetemp.puts epochtime

timetemp.close # always close files

#output information for copying
puts "customer|topic"
puts "Start: #{starttime}"
puts ""

start_record.rb gets the current time in epoch-seconds and writes it to a file called timetemp.txt in the same directory. Nothing new here, but I like the construct timetemp.puts epochtime, Ruby is very clean. 😉

When you’re done, end_record.rb is used to read in the starting time and to perform the necessary calculations:


#!/usr/bin/ruby

# Variables
endtime = Time.now
endsecs = endtime.to_i

# open the file
timetemp = File.open("timetemp.txt")

startsecs = timetemp.readline.to_i

timetemp.close # always close files

#calculations
starttime = Time.at(startsecs)

timesecs = endsecs - startsecs

timeminutes = (timesecs.to_f / 60)

timehours = (timeminutes / 60)

# output results
puts "Start: #{starttime}"
puts "End: #{endtime}"
puts "Seconds: #{timesecs}"
puts "Minutes: #{timeminutes}"
puts "Hours: #{timehours}"
puts ""
puts "Bill: "
puts ""

If you don’t want to copy and paste from the terminal-window, simply pipe the results to a file like this:

$ > ruby start_record.rb > my_file.txt

and when you’re done

$ > ruby end_record.rb >> my_file.txt

Remember though, > means overwrite the file if it exists. If you want to append, use >>. This might be obvious to most people fluent in UNIX, but should be noted as a “just in case you need to know”. 😉

Technorati Tags: , , , ,

Post a Comment

Your email is never published nor shared. Required fields are marked *, comments are moderated.

*
*