Last Updated: February 25, 2016
·
755
· ktkaushik

converting distance_of_time_in_words to seconds

# DOES NOT HANDLE 'half a minute','about a minute' among others
# dotiw is the distance_of_time_in_words
if dotiw
# split it with ' ' and get an array.
# Your array contains things such as :
# ["1", "year,", "11", "months,", "27", "days,", "13", "hours,", "and", "39", "minutes"]
split_distance_of_time_into_array = dotiw.split(' ')
total_time=0
split_distance_of_time_into_array.each_with_index do |t,index|
  # Converting any string into integer with no actual integer value inside would return zero.
  if t.to_i.zero?
    # If t is 'year' then its predecessor in the array has to be the no of years
    count = split_distance_of_time_into_array[index-1].to_i
    # t could be 'month', 'months', 'months,' or even 'month,'
    # Thus, split it with ','
    time_unit = t.split(',').first
  end

  # Converting the count of whatever time_unit into seconds here
  # ex :
  #     count = 3
  #     time_unit = month
  #     3.months.to_i => 7776000
  if t != "and" and t != "and," and !count.nil? and !time_unit.nil?
    total_time += count.send(time_unit).to_i
  end
end
end