Skip to content

Instantly share code, notes, and snippets.

@havran
Created June 2, 2017 08:27
Show Gist options
  • Save havran/f1e8d12d5d6adb741e816c8d42c4c9ae to your computer and use it in GitHub Desktop.
Save havran/f1e8d12d5d6adb741e816c8d42c4c9ae to your computer and use it in GitHub Desktop.
# Compute previous scheduled date.
def get_previous_day(date, day_of_week)
date = date.to_date
date - ((date.wday - day_of_week) % 7)
end
def get_previous_month_day(date, day_of_month)
date = date.to_date
if date.mday <= day_of_month
date.beginning_of_month + (day_of_month - 1).days - 1.month
else
date.beginning_of_month + (day_of_month - 1).days
end
end
def get_previous_2week_day(date, start_date, day_of_week)
date = date.to_date
previous_day = date - ((date.wday - day_of_week) % 7)
previous_previous_day = previous_day - 7.days
start_date = start_date.to_date
weeks = ((date - start_date.to_date)/7).to_i
week_multiplier = (weeks % 2) == 0
# puts "#{date} #{start_date} #{week_multiplier} #{previous_day} #{previous_previous_day}"
if date >= start_date
if week_multiplier
date.wday == day_of_week ? date : previous_day
else
date.wday == day_of_week ? date - 7.days : previous_previous_day
end
else
# ???
end
end
# get_previous_2week_day(Date.new(2016,2,19),Date.new(2016,2,18),4)
# Compute next scheduled date.
def get_next_day(date, day_of_week)
date = date.to_date
date + ((day_of_week - date.wday) % 7)
end
def get_next_month_day(date, day_of_month)
date = date.to_date
if date.mday <= day_of_month
date.beginning_of_month + (day_of_month - 1).days
else
date.beginning_of_month + (day_of_month - 1).days + 1.month
end
end
# Compute next day in two weeks interval from start_date.
# date - current day (today)
# start_date - date from which interval started
# day_of_week - day of week as number monday = 1 ... sunday = 0
def get_next_2week_day(date, start_date, day_of_week)
date = date.to_date
next_day = date + ((day_of_week - date.wday) % 7)
next_next_day = next_day + 7.days
start_date = start_date.to_date
weeks = ((date - start_date.to_date)/7).to_i
week_multiplier = (weeks % 2) == 0
# puts "#{date} #{start_date} #{week_multiplier} #{next_day} #{next_next_day}"
if date >= start_date
if week_multiplier
date.wday == day_of_week ? date : next_next_day
else
date.wday == day_of_week ? next_next_day : next_day
end
else
# ???
end
end
# get_next_2week_day(Date.new(2016,2,5),Date.new(2016,2,4),4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment