Skip to content

Fix Time.strptime %j with an offset landing on the wrong day - #93

Open
bardrop wants to merge 1 commit into
ruby:masterfrom
bardrop-oss:fix-strptime-yday-offset
Open

bardrop wants to merge 1 commit into
ruby:masterfrom
bardrop-oss:fix-strptime-yday-offset

Conversation

@bardrop

@bardrop bardrop commented Nov 18, 2026

Copy link
Copy Markdown

Time.strptime with %j and an offset can land on the wrong day:

require "time"

Time.strptime("1985-062 14:58:14 -1130", "%Y-%j %H:%M:%S %z")
# master:  1985-03-06 14:58:14 -1130
# this PR: 1985-03-03 14:58:14 -1130   (day 62 of 1985 is Mar 3)

Time.strptime("2030-060 20:18:28 -0345", "%Y-%j %H:%M:%S %z")
# master:  2030-03-02 20:18:28 -0345
# this PR: 2030-03-01 20:18:28 -0345

DateTime.strptime("1985-062 14:58:14 -1130", "%Y-%j %H:%M:%S %z")
# => #<DateTime: 1985-03-03T14:58:14-11:30 ...>

The cause is in make_time: it first guesses mon, day = (yday-1).divmod(31), which is often not a real date (day 62 → Feb 31). With a zone, apply_offset then moves that date, and when the day goes past the end of the month it resets to day 1 and loses the overflow. The diff/retry step can't recover from that.

This walks the months with month_days to get the real month and day, and then calls make_time once. When there's no year it uses the same year the rest of make_time would take from now. Day 366 in a common year still raises ArgumentError.

Checked 60k random %Y-%j / %j %Y strings (with and without %z / %:z, offsets -12:00..+14:45, years 1901-2100) against DateTime.strptime: master gets 95 wrong, this PR 0, with TZ set to UTC, America/New_York and Pacific/Chatham.

Added test_strptime_j_with_offset (fails on master). rake test passes with TZ=UTC, America/New_York, Asia/Tokyo and Pacific/Chatham.

Note: #91 sends ISO week dates through this same yday path, so it hits this too (left a comment there).

make_time guessed a month and day from yday ((yday-1).divmod(31)), which is
often not a real date (e.g. Feb 31). With a zone, apply_offset then moved
that invalid date and lost the overflow, so a late time with a negative
offset could end up days off:

    Time.strptime("1985-062 14:58:14 -1130", "%Y-%j %H:%M:%S %z")
    # => 1985-03-06 14:58:14 -1130, expected 1985-03-03

Walk the months with month_days to get the real month and day instead.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

⌂ Proxy