Life as Clay

Ruby snipped to return elapsed time as text

leave a comment »


I sometimes put code on the blog here that i want to be able to locate later. Here’s a bit of that. I use this (mainly with the “text” parameter) to return in text the time elapsed between a start_time DateTime stamp and an end_time DateTime stamp. It’s not perfect, but works well enough for my needs:

 

def duration(display)
    if start_time.nil? || end_time.nil? || start_time.blank? || end_time.blank?
      return ""
    end
    
    seconds = end_time - start_time
    minutes = seconds.to_i / 60
    hours = minutes.to_i / 60
    days = hours.to_i / 24
    
    new_hours = hours - (days * 24)
    new_minutes = minutes - (hours * 60)
    
    case display
      when "minutes"
        return new_minutes
      when "minutes_total"
        return minutes
      when "hours"
        return new_hours
      when "hours_total"
        return hours
      when "days"
        return days
      when "text"
        the_string = ""
    
        if days == 1
          the_string += "1 day "
        elsif days > 0
          the_string += days.to_s + " days "
        end
    
        if new_hours == 1
          the_string += "1 hour "
        elsif new_hours > 0
          the_string += new_hours.to_s + " hours "
        end 
    
        if new_minutes == 1
          the_string += "1 minute "
        else
          the_string += new_minutes.to_s + " minutes"
        end
    
        return the_string
      when "text_short"
        the_string = ""
    
        if days == 1
          the_string += "1 d "
        elsif days > 0
          the_string += days.to_s + " d "
        end
    
        if new_hours == 1
          the_string += "1 h "
        elsif new_hours > 0
          the_string += new_hours.to_s + " h "
        end 
    
        if new_minutes == 1
          the_string += "1 m "
        else
          the_string += new_minutes.to_s + " m"
        end
    end
    
  end
Advertisements

Written by Clay

November 16, 2011 at 12:32

Posted in Code, Ruby

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: