# Time calculate method in rails

**URL:** <https://www.ruby-forum.com/t/time-calculate-method-in-rails/172172>\
**Category:** Rails\
**Created:** [July 16, 2009, 6:22am UTC](https://www.ruby-forum.com/t/time-calculate-method-in-rails/172172 "2009-07-16T06:22:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![on9west](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/6f9a4e/32.png) [@on9west](https://www.ruby-forum.com/u/on9west)\
**Post date:** [July 16, 2009, 6:22am UTC](https://www.ruby-forum.com/t/time-calculate-method-in-rails/172172/1 "2009-07-16T06:22:36Z")

</div>

Dear all

Is there any existing function in rails to calculate time? I have google  
it but no information found…

For example  
a = “2009-07-16 12:34”.to\_time  
b = “2009-07-16 12:04”.to\_time  
some\_method(a,b) return “30 mins ago”

c = “2009-07-16 12:34”.to\_time  
d = “2009-07-12 09:09”.to\_time  
some\_method(c,d) return “4 days ago”

If not, I will write it by my own. But it can save my time if there is  
existing method to do so…

Many thanks  
Valentino

---

<div class="post-metadata">

**Author:** ![on9west](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/6f9a4e/32.png) [@on9west](https://www.ruby-forum.com/u/on9west)\
**Post date:** [July 16, 2009, 8:29am UTC](https://www.ruby-forum.com/t/time-calculate-method-in-rails/172172/2 "2009-07-16T08:29:36Z")

</div>

2009/7/16 Valentino L. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> c = “2009-07-16 12:34”.to\_time  
> d = “2009-07-12 09:09”.to\_time  
> some\_method(c,d) return “4 days ago”
> 
> If not, I will write it by my own. But it can save my time if there is  
> existing method to do so…

Have a look at the documentation for the Time class. You can just  
subtract the times.

> > a = “2009-07-16 12:34”.to\_time  
> > =\> Thu Jul 16 12:34:00 UTC 2009  
> > b = “2009-07-16 12:04”.to\_time  
> > =\> Thu Jul 16 12:04:00 UTC 2009  
> > diff = a-b  
> > =\> 1800.0 # 30 mins in seconds

Colin

---

<div class="post-metadata">

**Author:** ![on9west](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/6f9a4e/32.png) [@on9west](https://www.ruby-forum.com/u/on9west)\
**Post date:** [July 16, 2009, 1:28pm UTC](https://www.ruby-forum.com/t/time-calculate-method-in-rails/172172/3 "2009-07-16T13:28:49Z")

</div>

You also can use the DateHelper ([http://api.rubyonrails.org/classes/](http://api.rubyonrails.org/classes/)  
ActionView/Helpers/DateHelper.html). Always the Rails API is the best  
place to start.

Regards.

Franco C…

On Jul 16, 1:22 am, Valentino L. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
