# Date time subtraction

**URL:** <https://www.ruby-forum.com/t/date-time-subtraction/171399>\
**Category:** Ruby\
**Created:** [July 1, 2009, 7:46pm UTC](https://www.ruby-forum.com/t/date-time-subtraction/171399 "2009-07-01T19:46:07Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![aidy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/eada6e/32.png) [@aidy](https://www.ruby-forum.com/u/aidy)\
**Post date:** [July 1, 2009, 7:46pm UTC](https://www.ruby-forum.com/t/date-time-subtraction/171399/1 "2009-07-01T19:46:07Z")

</div>

Hi,

I am trying to do a subtraction of the date and time in the format  
below with the current date and time

“2009-07-01 18:24:20”

Will I need to tokenise this string and do individual number  
comparisons?

Thanks

Aidy

---

<div class="post-metadata">

**Author:** ![aidy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/eada6e/32.png) [@aidy](https://www.ruby-forum.com/u/aidy)\
**Post date:** [July 1, 2009, 7:50pm UTC](https://www.ruby-forum.com/t/date-time-subtraction/171399/2 "2009-07-01T19:50:48Z")

</div>

aidy wrote:

> Hi,
> 
> I am trying to do a subtraction of the date and time in the format  
> below with the current date and time
> 
> “2009-07-01 18:24:20”
> 
> Will I need to tokenise this string and do individual number  
> comparisons?

irb(main):007:0\> require ‘time’  
=\> true  
irb(main):009:0\> t = Time.parse “2009-07-01 18:24:20”  
=\> Wed Jul 01 18:24:20 -0700 2009  
irb(main):010:0\> t.to\_i  
=\> 1246497860  
irb(main):011:0\> t.day  
=\> 1  
irb(main):012:0\> t.hour  
=\> 18

See the Time class for details. You can also directly compare time  
objects (without using to\_i to get seconds since the epoch):

irb(main):013:0\> Time.now \< Time.now  
=\> true

---

<div class="post-metadata">

**Author:** ![aidy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/eada6e/32.png) [@aidy](https://www.ruby-forum.com/u/aidy)\
**Post date:** [July 1, 2009, 7:54pm UTC](https://www.ruby-forum.com/t/date-time-subtraction/171399/3 "2009-07-01T19:54:54Z")

</div>

Joel VanderWerf wrote:

> See the Time class for details. You can also directly compare time  
> objects (without using to\_i to get seconds since the epoch):

And you can also subtract Time objects to get seconds:

irb(main):016:0\> t - Time.now  
=\> 27032.573318

---

<div class="post-metadata">

**Author:** ![aidy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/eada6e/32.png) [@aidy](https://www.ruby-forum.com/u/aidy)\
**Post date:** [July 1, 2009, 8:00pm UTC](https://www.ruby-forum.com/t/date-time-subtraction/171399/4 "2009-07-01T20:00:44Z")

</div>

On 1 July, 18:50, Joel VanderWerf [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> irb(main):007:0\> require ‘time’  
> =\> true  
> irb(main):009:0\> t = Time.parse “2009-07-01 18:24:20”  
> =\> Wed Jul 01 18:24:20 -0700 2009

Thanks Joel.

Aidy
