Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the number of weeks since a given date in Ruby?

Objective

I am trying to calculate the distance in weeks since a given date without jumping through hoops. I'd prefer to do it in plain Ruby, but ActiveSupport is certainly an acceptable alternative.

My Code

I wrote the following, which seems to work but looks like the long way around to me.

require 'date'

DAYS_IN_WEEK = 7.0 

def weeks_since date_string
  date  = Date.parse date_string
  days  = Date.today - date
  weeks = days / DAYS_IN_WEEK
  weeks.round 2
end

weeks_since '2015-06-15'
#=> 32.57

ActiveSupport's #weeks_since takes a number of weeks as its argument, so it doesn't fit this use case. Ruby's Date class doesn't seem to have anything relevant, either.

Alternatives?

Is there a better built-in solution or well-known algorithm for calculating the number of weeks separating a pair of dates? I'm not trying to code-golf this, as readability trumps brevity, but simply to learn whether Ruby natively supports the type of date arithmetic I've coded by hand.

like image 474
Todd A. Jacobs Avatar asked Jan 29 '16 17:01

Todd A. Jacobs


People also ask

How do you calculate weeks to date?

Weeks between datesDivide the number of days by 7 and round down. You will get the number of full weeks. Calculate the integer remainder after dividing the number of days by 7. You will get the number of days.

How does rails calculate date difference?

With the Date (and DateTime) classes you can do (end_date - start_date). to_i to get the number of days difference.

How do I calculate the number of weeks between two dates in PHP?

php function week_between_two_dates($date1, $date2) { $first = DateTime::createFromFormat('m/d/Y', $date1); $second = DateTime::createFromFormat('m/d/Y', $date2); if($date1 > $date2) return week_between_two_dates($date2, $date1); return floor($first->diff($second)->days/7); } $dt1 = '1/1/2014'; $dt2 = '12/31/2014'; ...

How do I get the last date of the month in Ruby?

Yes you can use Date. new(year, month, -1).


2 Answers

Might be easier to convert the dates to time and then divide the time difference by a week. You can round it however you want or ceil.

def weeks_since(date_string)
  time_in_past = Date.parse(date_string).to_time
  now = Time.now
  time_difference = now - time_in_past
  (time_difference / 1.week).round(2)
end
like image 57
Marcus Hoile Avatar answered Oct 16 '22 05:10

Marcus Hoile


in_weeks (Rails 6.1+)

Rails 6.1 introduces new ActiveSupport::Duration conversion methods like in_seconds, in_minutes, in_hours, in_days, in_weeks, in_months, and in_years.

As a result, now, your problem can be solved as:

date_1 = Time.parse('2020-10-18 00:00:00 UTC')
date_2 = Time.parse('2020-08-13 03:35:38 UTC') 

(date_2 - date_1).seconds.in_weeks.to_i.abs
# => 9

Here is a link to the corresponding PR.

like image 38
Marian13 Avatar answered Oct 16 '22 04:10

Marian13