Sha256: dfcd99bce712fde6c4afe3ff13f2bf0174634fe91ac031f9ccca4f40f177f586

Contents?: true

Size: 821 Bytes

Versions: 10

Compression:

Stored size: 821 Bytes

Contents

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 => e
      raise DateFormatException, "Date #{self} is invalid or not formatted correctly."
    end
  end

  class DateFormatException < Exception; end
end

class String
  include Timely::String
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
timely-0.5.0 lib/timely/string.rb
timely-0.4.2 lib/timely/string.rb
timely-0.4.1 lib/timely/string.rb
timely-0.4.0 lib/timely/string.rb
timely-0.3.4 lib/timely/string.rb
timely-0.3.2 lib/timely/string.rb
timely-0.3.1 lib/timely/string.rb
timely-0.3.0 lib/timely/string.rb
timely-0.1.0 lib/timely/string.rb
timely-0.0.2 lib/timely/string.rb