Skip to content

Instantly share code, notes, and snippets.

@abhianair
Created February 11, 2020 06:07
Show Gist options
  • Save abhianair/b5a904e0dc2bff8122b3f0c50f817cd9 to your computer and use it in GitHub Desktop.
Save abhianair/b5a904e0dc2bff8122b3f0c50f817cd9 to your computer and use it in GitHub Desktop.
Gross and Effective time from an array of time DateTime objects
def task_overalltime(timelines)
array = timelines.split(',').map{ |x| x.to_datetime}
nd_time = array.length.even? ? '' : '+'
array = array.reverse
rec_difference = 0
array.each_with_index do |val, ind|
if ind.odd?
next_ind = ind - 1
rec_difference = rec_difference + (val.to_time - array[next_ind].to_time).to_i.abs if array[next_ind].present?
end
end
effect_time = get_effective_time(rec_difference)
gross = time_diff(array.first.to_time, array.last.to_time)
return "Gross Time : #{gross}#{nd_time} Effective Time: #{effect_time}#{nd_time}"
end
def get_effective_time(seconds_diff)
hours = seconds_diff / 3600
seconds_diff -= hours * 3600
minutes = seconds_diff / 60
seconds_diff -= minutes * 60
seconds = seconds_diff
"#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
end
def time_diff(start_time, end_time)
seconds_diff = (start_time - end_time).to_i.abs
hours = seconds_diff / 3600
seconds_diff -= hours * 3600
minutes = seconds_diff / 60
seconds_diff -= minutes * 60
seconds = seconds_diff
"#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
# or, as hagello suggested in the comments:
# '%02d:%02d:%02d' % [hours, minutes, seconds]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment