datetime - Time operations in ruby -


i new ruby. trying calculate number of seconds given period. have start time , end time hh:mm:ss format.

can declare variable object of time class , perform calculations? example:

start_time='15:00:12' end_time='19:32:12' a=time.new(start_time) b=time.new(end_time) duration_seconds=a-b 

here code in ruby

since time.new expects parameters year, month, day, hour, minute, seconds - have used current time first 3 parameter, , values string parameter op had rest of 3 parameters

getting difference between 2 time - have used to_i method returns number of seconds epoch time instance represents

string_start_time ='15:00:12' start_time_parts = string_start_time.split(":").collect{ |y| y.to_i } start_time = time.new(time.now.year, time.now.month, time.now.day, start_time_parts[0], start_time_parts[1], start_time_parts[2]) p start_time  string_end_time='19:32:12' end_time_parts = string_end_time.split(":").collect{ |y| y.to_i } end_time = time.new(time.now.year, time.now.month, time.now.day, end_time_parts[0], end_time_parts[1], end_time_parts[2]) p end_time  p duration_seconds = end_time.to_i - start_time.to_i 

note: code refactoring needed extract function create time hh:mm:ss, have duplicate code

output of above code be

2015-07-14 15:00:12 +0530 2015-07-14 19:32:12 +0530 16320 [finished in 0.1s] 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -