Skip to content

Instantly share code, notes, and snippets.

@victorbstan
Created July 7, 2011 19:21
Show Gist options
  • Save victorbstan/1070318 to your computer and use it in GitHub Desktop.
Save victorbstan/1070318 to your computer and use it in GitHub Desktop.
count days between two dates
# definition
# provide an optional day name (in English)
# as the last parameter to get the number of times that day occurs
# between the two provided dates
#
# dates (t1 and t2) should be valid Time object dates
def list_days_between(t1, t2, day_name=nil)
days = []
(t2.to_i..t1.to_i).step(86400) do |t|
days << Time.at(t).strftime('%A')
end
if day_name
days.collect! { |d| d if d == day_name }
days.delete_if {|d| d == nil}
days = days.count
end
days
end
# use
now = Time.now
# according to Google: 10 000 000 seconds = 115.740741 days
# note: I make no claim about the efficiency of this algorithm...
# improvement suggestions are welcome!
day_names_count = list_days_between(now, now-10000000, 'Saturday')
day_names = list_days_between(now, now-10000000)
puts 'Array of days: ' + day_names.inspect
puts 'Count of Saturdays: ' + day_names_count.inspect
puts 'Total days:' + day_names.count.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment