Class: Delocalize::Parsers::DateTime

Inherits:
Object
  • Object
show all
Defined in:
lib/delocalize/parsers/date_time.rb

Constant Summary collapse

REGEXPS =

extend/change this according to your needs by merging your custom regexps

{
  '%B' => "(#{Date::MONTHNAMES.compact.join('|')})",      # long month name
  '%b' => "(#{Date::ABBR_MONTHNAMES.compact.join('|')})", # short month name
  '%m' => "(\\d{2})",                                     # numeric month
  '%A' => "(#{Date::DAYNAMES.join('|')})",                # full day name
  '%a' => "(#{Date::ABBR_DAYNAMES.join('|')})",           # short day name
  '%Y' => "(\\d{4})",                                     # long year
  '%y' => "(\\d{2})",                                     # short year
  '%e' => "(\\s\\d|\\d{2})",                              # short day
  '%d' => "(\\d{2})",                                     # full day
  '%H' => "(\\d{2})",                                     # hour (24)
  '%M' => "(\\d{2})",                                     # minute
  '%S' => "(\\d{2})"                                      # second
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ DateTime

Returns a new instance of DateTime.



27
28
29
# File 'lib/delocalize/parsers/date_time.rb', line 27

def initialize(type)
  @type = type
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



25
26
27
# File 'lib/delocalize/parsers/date_time.rb', line 25

def type
  @type
end

Instance Method Details

#parse(datetime) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/delocalize/parsers/date_time.rb', line 31

def parse(datetime)
  return unless datetime
  return datetime if datetime.respond_to?(:strftime) # already a Date/Time object -> no need to parse it

  translate_month_and_day_names(datetime)
  input_formats(type).each do |original_format|
    next unless datetime =~ /^#{apply_regex(original_format)}$/

    datetime = ::DateTime.strptime(datetime, original_format) rescue break
    return Date == type ?
      datetime.to_date :
      Time.zone.local(datetime.year, datetime.mon, datetime.mday, datetime.hour, datetime.min, datetime.sec)
  end
  default_parse(datetime, type)
end