Module: Lazier::DateTime

Extended by:
ActiveSupport::Concern
Defined in:
lib/lazier/datetime.rb

Overview

Extensions for date and time objects.

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#format(format = nil, custom: true, change_time_zone: false) ⇒ String

Formats a datetime, eventually looking up also custom formats and/or moving to the current timezone.

Parameters:

  • format (String|NilClass) (defaults to: nil)

    A format or a custom format name to use for formatting.

  • custom (Boolean) (defaults to: true)

    Whether to use custom formats.

  • change_time_zone (Boolean) (defaults to: false)

    Whether to move the date to the current timezone.

Returns:

  • (String)

    The formatted date.

See Also:



171
172
173
174
175
# File 'lib/lazier/datetime.rb', line 171

def format(format = nil, custom: true, change_time_zone: false)
  target = change_time_zone && respond_to?(:in_time_zone) ? in_time_zone : self
  format = custom ? ::DateTime.custom_format(format.to_s).gsub(/(?<!%)(%[ab])/i) { |mo| localize_time_component(mo) } : format.to_s
  target.strftime(format)
end

#months_since_year(base = nil) ⇒ Fixnum

Returns the number of months passed between the beginning of the base year and the current date.

Example:

DateTime.civil(2013, 6, 1).in_months(2011)
# => 18

Parameters:

  • base (DateTime|NilClass) (defaults to: nil)

    The base year to start computation from. Default to current year.

Returns:

  • (Fixnum)

    Returns the number of months passed between the beginning of the base year and the current date.



153
154
155
# File 'lib/lazier/datetime.rb', line 153

def months_since_year(base = nil)
  (year - (base || ::Date.today.year)) * 12 + month
end

#padded_monthString

Returns the current month number with a leading zero if needed.

Returns:

  • (String)

    The current month number with leading zero if needed.



160
161
162
# File 'lib/lazier/datetime.rb', line 160

def padded_month
  month.indexize
end