Sha256: 1040021a6c1246947419f0a586c11fa6fc2d6cd3ce8ef2702a3e591372978f08

Contents?: true

Size: 850 Bytes

Versions: 9

Compression:

Stored size: 850 Bytes

Contents

# frozen_string_literal: true

module Timely
  module String
    # fmt e.g. '%d/%m/%Y'
    # By default it will try to guess the format
    # If using ActiveSupport you can pass in a symbol for the DATE_FORMATS
    def to_date(fmt = nil)
      if fmt
        fmt = Date::DATE_FORMATS[fmt] if fmt.is_a?(Symbol) && defined?(Date::DATE_FORMATS)
        parsed = ::Date._strptime(self, fmt)
        parsed[:year] = parsed[:year] + 2000 if parsed[:year] < 1000
        ::Date.new(*parsed.values_at(:year, :mon, :mday))
      else
        ::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
      end
    rescue NoMethodError, ArgumentError
      raise DateFormatException, "Date #{self} is invalid or not formatted correctly."
    end
  end

  class DateFormatException < RuntimeError; end
end

class String
  include Timely::String
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
timely-0.14.0 lib/timely/string.rb
timely-0.13.0 lib/timely/string.rb
timely-0.12.0 lib/timely/string.rb
timely-0.11.0 lib/timely/string.rb
timely-0.10.0 lib/timely/string.rb
timely-0.9.0 lib/timely/string.rb
timely-0.8.0 lib/timely/string.rb
timely-0.7.0 lib/timely/string.rb
timely-0.6.0 lib/timely/string.rb