Skip to content

Commit

Permalink
handle mixtures of commercial dates and non commercial
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuacronemeyer committed Aug 12, 2023
1 parent b8abcaf commit 92654d1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
20 changes: 9 additions & 11 deletions lib/timecop/time_extensions.rb
Expand Up @@ -50,24 +50,22 @@ def strptime_with_mock_date(str = '-4712-01-01', fmt = '%F', start = Date::ITALY

d = Date._strptime(str, fmt)
now = Time.now.to_date
year = d[:year] || now.year
year = d[:year] || d[:cwyear] || now.year
mon = d[:mon] || now.mon
if d.keys == [:year]
Date.new(year, 1, 1, start)
elsif d[:mday]
Date.new(year, mon, d[:mday], start)
elsif d[:wday]
Date.new(year, mon, now.mday, start) + (d[:wday] - now.wday)
elsif d[:yday]
Date.new(year, 1, 1, start).next_day(d[:yday] - 1)
elsif d[:cwyear] && d[:cweek]
if d[:cwday]
Date.commercial(d[:cwyear], d[:cweek], d[:cwday], start)
else
Date.commercial(d[:cwyear], d[:cweek], 1, start)
end
elsif d[:wnum1]
Date.commercial(year, d[:wnum1], 1, start)
elsif d[:cwyear] || d[:cweek] || d[:wnum1] || d[:wday] || d[:cwday]
day_of_week_from_monday = if d[:wday]
(d[:wday] + 6)%7 + 1
else
d[:cwday] || 1
end
week = d[:cweek] || d[:wnum1] || now.strftime('%W').to_i
Date.commercial(year, week, day_of_week_from_monday, start)
elsif d[:seconds]
Time.at(d[:seconds]).to_date
else
Expand Down
13 changes: 13 additions & 0 deletions test/date_strptime_scenarios.rb
Expand Up @@ -31,6 +31,11 @@ def test_date_strptime_with_commercial_week_date
assert_equal Date.strptime('1984-09', '%G-%V'), Date.new(1984, 2, 27)
end

def test_date_strptime_with_commercial_week_date_and_day_of_week_from_sunday
assert_equal Date.strptime('1984-09-0', '%G-%V-%w'), Date.new(1984, 3, 04)
assert_equal Date.strptime('1984-09-1', '%G-%V-%u'), Date.new(1984, 2, 27)
end

def test_date_strptime_with_iso_8601_week_date
assert_equal Date.strptime('1984-W09-1', '%G-W%V-%u'), Date.new(1984, 2, 27)
end
Expand All @@ -39,10 +44,18 @@ def test_date_strptime_with_year_and_week_number_of_year
assert_equal Date.strptime('201810', '%Y%W'), Date.new(2018, 3, 5)
end

def test_date_strptime_with_year_and_week_number_of_year_and_day_of_week_from_monday
assert_equal Date.strptime('2018107', '%Y%W%u'), Date.new(2018, 3, 11)
end

def test_date_strptime_with_just_week_number_of_year
assert_equal Date.strptime('14', '%W'), Date.new(1984, 4, 02)
end

def test_date_strptime_week_of_year_and_day_of_week_from_sunday
assert_equal Date.strptime('140', '%W%w'), Date.new(1984, 4, 8)
end

def test_date_strptime_with_seconds_since_epoch
assert_equal Date.strptime('446731200', '%s'), Date.new(1984, 2, 27)
end
Expand Down

0 comments on commit 92654d1

Please sign in to comment.