Last active
December 7, 2017 03:35
-
-
Save nelsonsar/4463ccfc002bc050308daae1707819e6 to your computer and use it in GitHub Desktop.
Ruby DateTime iso8601 for week dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DateTime | |
# Regex to match Week date from ISO8601 represented as YYYY-Www | |
# For more information about Week date see: https://en.wikipedia.org/wiki/ISO_8601#Week_dates | |
# | |
SHORT_FORMAT_WEEK_DATE_REGEX = /\A[0-9]{4}-W([0-4]\d|5[0-2])\z/.freeze | |
class << self | |
alias_method :ruby_iso8601, :iso8601 | |
# Since Ruby supports the longer week date (YYYY-Www-D) and 2017-W29 is the | |
# same as write 2017-W29-1 we just add the week day when the given "string" | |
# parameter is the shorter version of a Week date. | |
# | |
def iso8601(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY) | |
date = string.to_s.dup | |
if SHORT_FORMAT_WEEK_DATE_REGEX.match?(date) | |
date << '-1' | |
end | |
ruby_iso8601(date, start) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment