class Formatter::Date

Date formatter with time zone support.

Constants

VERSION

Gem version

Attributes

formatter[R]
time_zone[R]

Public Class Methods

new(time_zone, format = :iso8601, fraction = 0) click to toggle source

Initialize a formatter with the desired options.

:time_zone specifies which time zone to use when formatting.

:format specifies which format to use, it can either be a symbol of a predefined format or a string with a custom format which will be delegated to DateTime#strftime.

:fraction is length of fractional seconds to be used with predefined formats.

@param [String|TZInfo::Timezone] time_zone @param [Symbol|String] format @param [Integer] fraction (0)

@return [undefined]

@api public

# File lib/formatter/date.rb, line 44
def initialize(time_zone, format = :iso8601, fraction = 0)
  self.time_zone = time_zone
  @formatter = formatter_for format, fraction
end

Public Instance Methods

format(time_or_datetime) click to toggle source

Format Time or DateTime with formatter

@param [Time|DateTime] time_or_datetime

@return [String]

@api public

# File lib/formatter/date.rb, line 56
def format(time_or_datetime)
  formatter.call with_offset(time_or_datetime)
end
identifier() click to toggle source

Configured time zone identifier

@return [String]

@api public

# File lib/formatter/date.rb, line 65
def identifier
  time_zone.identifier
end
offset() click to toggle source

Configured time zone offset

@return [Rational]

@api public

# File lib/formatter/date.rb, line 74
def offset
  time_zone.current_period.utc_total_offset_rational
end

Private Instance Methods

format_method?(method) click to toggle source
# File lib/formatter/date.rb, line 106
def format_method?(method)
  %w(iso8601 xmlschema jisx0301 rfc3339).include? method.to_s
end
formatter_for(format, fraction) click to toggle source
# File lib/formatter/date.rb, line 93
def formatter_for(format, fraction)
  case format
  when Symbol
    if format_method? format
      return -> datetime { datetime.send format, fraction }
    end
  when String
    return -> datetime { datetime.strftime format }
  end

  fail ArgumentError, "invalid value for format: #{format.inspect}"
end
time_zone=(time_zone) click to toggle source
# File lib/formatter/date.rb, line 82
def time_zone=(time_zone)
  case time_zone
  when String
    @time_zone = TZInfo::Timezone.get time_zone
  when TZInfo::DataTimezone
    @time_zone = time_zone
  else
    fail ArgumentError, "invalid time zone: #{time_zone.inspect}"
  end
end
with_offset(time_or_datetime) click to toggle source
# File lib/formatter/date.rb, line 110
def with_offset(time_or_datetime)
  TimeOrDateTime.new(time_or_datetime).to_datetime.new_offset offset
end