How to parse and generate week strings for HTML week elements in Ruby/Rails?

7 hours ago 1
ARTICLE AD BOX

HTML has a week selector <input type="week"> which provides a string such as 2026-W05 (Week 5 of 2026).

Ruby provides the strptime/strftime methods which seem to be able to handle this using the format "%G-W%V".
So I used these methods with the examples provided on MDN here but it failed to produce the same results (code below).

Is there a better way to handle these inputs with Ruby or Rails?

class DateHelper # Parse a string provided by a HTML week input def self.parse_iso8601_week(string) Date.strptime(string, "%G-W%V").all_week end def self.to_iso8601_week(date_range) date_range.first.strftime("%G-W%V") end end describe DateHelper, "iso8601 (HTML spec) week conversions" do RSpec.shared_examples "conversion" do |iso_week, start_date, end_date| it do result = DateHelper.parse_iso8601_week(iso_week) # converts to a date range expect(result).to eq start_date.to_date..end_date.to_date # converts back to the same string expect(DateHelper.to_iso8601_week(result)).to eq iso_week end end include_examples "conversion", "2001-W37", "2001-09-10", "2001-09-16" include_examples "conversion", "1953-W01", "1952-12-29", "1953-01-04" include_examples "conversion", "1948-W53", "1948-12-27", "1949-01-02" include_examples "conversion", "1949-W01", "1949-01-03", "1949-01-09" end

Results:

DateHelper iso8601 (HTML spec) week conversions is expected to eq "2001-W37" is expected to eq Mon, 29 Dec 1952..Sun, 04 Jan 1953 (FAILED - 1) example at ./spec/lib/date_helper_spec.rb:83 (FAILED - 2) # Date::Error: invalid date is expected to eq "1949-W01"
Read Entire Article