# frozen_string_literal: true require 'dates_toolbox/version' require 'dates_toolbox/overloads' require 'date' # # Docs to follow # class Date attr_accessor :format # rubocop:disable Lint/DuplicateMethods def format @format || '%d/%m/%Y' end # rubocop:enable Lint/DuplicateMethods def test_format (parse_date('1/1/1970', format).wday == 6) end def parse_date(date1, format_string) begin return Date.strptime(date1, format_string) rescue ArgumentError => e puts "Invalid date #{date1} with format #{format}" throw e end end def the_day(date1, format_string = format) parse_date(date1, format_string).day end def the_month(date1, format_string = format) parse_date(date1, format_string).month end def the_year(date1, format_string = format) parse_date(date1, format_string).year end def dotw(date1, format_string = format) day_of_the_week(date1, format_string) end def day_of_the_week(date1, format_string = format) parse_date(date1, format_string).wday end def dotwn(date1, format_string = format) day_of_the_week_name(date1, format_string) end def day_of_the_week_name(date1, format_string = format) Date::DAYNAMES[day_of_the_week(date1, format_string)] end def doty(date1, format_string = format) day_of_the_year(date1, format_string) end def day_of_the_year(date1, format_string = format) parse_date(date1, format_string).yday end def days_between(date1, date2, format_string = format) d1 = parse_date(date1, format_string) d2 = parse_date(date2, format_string) d2.mjd - d1.mjd end def weekends(date1, date2, format_string = format) start_date = parse_date(date1, format_string) end_date = parse_date(date2, format_string) # day of the week in 0-6. Sunday is day-of-week 0; Saturday is day-of-week 6. my_days = [0, 6] (start_date..end_date).to_a.select { |k| my_days.include?(k.wday) } end def weekends_string(date1, date2, format_string = format) weekends(date1, date2, format_string).map { |n| n.strftime(format) } end def weekdays(date1, date2, format_string = format) start_date = parse_date(date1, format_string) end_date = parse_date(date2, format_string) # day of the week in 0-6. Sunday is day-of-week 0; Saturday is day-of-week 6. my_days = (1..5).to_a (start_date..end_date).to_a.select { |k| my_days.include?(k.wday) } end def weekdays_string(date1, date2, format_string = format) weekdays(date1, date2, format_string).map { |n| n.strftime(format) } end end