Mateusz Urbański
Mateusz Urbański

Reputation: 7862

Calculations on datetime range

I have a problem with calculation on datetime fields. I have two variables:

a = Sat, 01 Feb 2014 13:00:00 CET +01:00

and

b = Fri, 28 Feb 2014 13:00:00 CET +01:00

And I want to calculate how many days passed from a to b range. Please Help.

Upvotes: 0

Views: 151

Answers (3)

Amit Sharma
Amit Sharma

Reputation: 3477

You can also use time_diff gem to calculate the difference.

In your gem file add gem 'time_diff'

I have added the code in index.html.erb but, you can use it any where you want.

take a look on following code.

<% require 'time_diff' %>

<% a = Time.diff(Time.parse('Sat, 01 Feb 2014 13:00:00 CET +01:00'), Time.parse('Fri, 28 Feb 2014 13:00:00 CET +01:00'), "%d") %>
<%= a[:diff] %>

and I got the following result

"27 days"

You can also take a look on https://github.com/abhidsm/time_diff

Upvotes: 1

Alok Anand
Alok Anand

Reputation: 3356

require 'date'


a=Date.parse('Sat, 01 Feb 2014 13:00:00 CET +01:00')
 => #<Date: 2014-02-01 (4913379/2,0,2299161)> 



 b=Date.parse('Fri, 28 Feb 2014 13:00:00 CET +01:00')
 => #<Date: 2014-02-28 (4913433/2,0,2299161)> 

b-a
 => (27/1) 

(b-a).to_i
 => 27 

Upvotes: 1

Babasaheb Gosavi
Babasaheb Gosavi

Reputation: 8025

You can use this.

require 'date'
( Date.parse('Fri, 28 Feb 2014 13:00:00 CET +01:00') - Date.parse('Sat, 01 Feb 2014 13:00:00 CET +01:00')).to_i
=> 27
i.e
 ( Date.parse(b) - Date.parse(a)).to_i    

Upvotes: 3

Related Questions