Note that there are some explanatory texts on larger screens.

plurals
  1. PODate, substraction, conditions and rendering
    text
    copied!<p>I'm currently trying to create a method that will substract two dates. Here's what it looks like : (maturity is a futur time) </p> <pre><code> def time_remaining # If validated, return time between now and number of days from validation. if self.is_validated? return (self.maturity &gt; Time.now) ? (self.maturity - Time.now) : 0 # If not validated, return number of days converted in time else return self.nb_days.nil? ? 0 : self.nb_days.days end end </code></pre> <p>And in my View my doing this :</p> <pre><code>distance_of_time_in_words(project.time_remaining) </code></pre> <p>This works but it isn't what I'm really trying to do, what I want is to retrieve a number of hours if the result of the substraction equals less than a day, to retrieve a number of minutes if the result of the substraction equals less than an hour and to retrieve a number of days if the result equals more than a day.</p> <p>maturity is under this format : <code>Wed, 27 Nov 2013 12:42:09 UTC +00:00</code>. Can you please tell me at least a hint about how can I do that ?</p> <p><strong>EDIT :</strong> </p> <p>I've tried something like this but it's really messy :</p> <pre><code>def time_remaining # If validated, return time between now and number of days from validation. if self.is_validated? if (self.maturity &gt; Time.now) if ((self.maturity - Time.now)/1.day &lt; 1) return (self.maturity - Time.now)/1.day. elsif ((self.maturity - Time.now) &lt; 1.hour) return (self.maturity - Time.now)/1.min else return (self.maturity - Time.now) end else 0 end # If not validated, return number of days converted in time else return self.nb_days.nil? ? 0 : self.nb_days.days end end </code></pre> <p>The point is to remove the <code>distance_of_time_in_words</code> here.</p> <p><strong>Solution :</strong> Thanks to @Rafał Cieślak and the gem time_diff. Here's what I've done :</p> <pre><code> def remaining_time (project) if project.is_validated? if ((project.maturity - Time.now)/1.day &gt;= 1) result = Time.diff(project.maturity, Time.now, '%d') return result[:diff] elsif ((project.maturity - Time.now)/1.hour &gt; 1 &amp;&amp; (project.maturity - Time.now)/1.hour &lt; 24) result = Time.diff(project.maturity, Time.now, '%H') return result[:diff] elsif ((project.maturity - Time.now)/1.hour &lt; 1) result = Time.diff(project.maturity, Time.now, '%N') return result[:diff] end else return project.nb_days.nil? ? 0 : project.nb_days.days end end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload