On Apr 16, 2008, at 6:24 AM, Jesù¸ Gabriel y GaláÏ wrote: > On Wed, Apr 16, 2008 at 11:56 AM, Clement Ow > <clement.ow / asia.bnpparibas.com> wrote: >> I have a program where i put the time at the beginning: >> puts $t1=Time.now >> >> and then after running some commands, i put the time again: >> puts $t2=Time.now >> >> and then have a method to calculate the time elapsed: >> def calTime >> starttime_sec= $t1.strftime("%S").to_i >> starttime_min= $t1.strftime("%M").to_i >> endtime_sec= $t2.strftime("%S").to_i >> endtime_min= $t2.strftime("%M").to_i >> diff_sec= endtime_sec - starttime_sec >> diff_sec1= diff_sec.to_s >> diff_min= endtime_min - starttime_min >> diff_min1= diff_min.to_s >> puts "\nElapsed time:\n "+ "Min-> " +diff_min1 + " Sec-> "+ diff_sec1 >> >> However, the calculation has limitations because if the start time is >> say, 4:50 and the end time is 5:10, it will return an errorneous >> value >> like -49 for the Min value, which is obviously not what we want.. >> >> Any alternative method or any corrections to the method are >> welcome. ;) > > Alternative: > > irb(main):001:0> start = Time.now > => Wed Apr 16 12:06:23 +0200 2008 > irb(main):003:0> finish = Time.now > => Wed Apr 16 12:07:24 +0200 2008 > irb(main):005:0> elapsed = (finish - start).to_i > => 65 > irb(main):012:0> mins = elapsed / 60 > => 1 > irb(main):013:0> secs = elapsed % 60 > => 5 > > Jesus. or: irb> start = Time.now => Wed Apr 16 10:41:03 -0400 2008 irb> finish = Time.now => Wed Apr 16 10:45:53 -0400 2008 irb> elapsed = finish.to_f - start.to_f # note to_f to keep fractional seconds => 289.695813894272 irb> mins, secs = elapsed.divmod 60.0 => [4, 49.6958138942719] irb> puts("%3d:%04.2f"%[mins.to_i, secs]) 4:49.70 => nil -Rob Rob Biedenharn http://agileconsultingllc.com