Method: TimeCalc::Diff#factorize

Defined in:
lib/time_calc/diff.rb

#factorize(zeroes: true, max: :year, min: :sec, weeks: true) ⇒ Hash<Symbol => Integer>

“Factorizes” the distance between two points in time into units: years, months, weeks, days.

Examples:

t1 = Time.parse('2019-06-01 14:50')
t2 = Time.parse('2019-06-15 12:10')
(TimeCalc.(t2) - t1).factorize
# => {:year=>0, :month=>0, :week=>1, :day=>6, :hour=>21, :min=>20, :sec=>0}
(TimeCalc.(t2) - t1).factorize(weeks: false)
# => {:year=>0, :month=>0, :day=>13, :hour=>21, :min=>20, :sec=>0}
(TimeCalc.(t2) - t1).factorize(weeks: false, zeroes: false)
# => {:day=>13, :hour=>21, :min=>20, :sec=>0}
(TimeCalc.(t2) - t1).factorize(max: :hour)
# => {:hour=>333, :min=>20, :sec=>0}
(TimeCalc.(t2) - t1).factorize(max: :hour, min: :min)
# => {:hour=>333, :min=>20}

Parameters:

  • zeroes (true, false) (defaults to: true)

    Include big units (for ex., year), if they are zero

  • weeks (true, false) (defaults to: true)

    Include weeks

  • max (Symbol) (defaults to: :year)

    Max unit to factorize into, from all supported units list

  • min (Symbol) (defaults to: :sec)

    Min unit to factorize into, from all supported units list

Returns:

  • (Hash<Symbol => Integer>)


160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/time_calc/diff.rb', line 160

def factorize(zeroes: true, max: :year, min: :sec, weeks: true)
  t = to
  f = from
  select_units(max: Units.(max), min: Units.(min), weeks: weeks)
    .inject({}) { |res, unit|
      span, t = Diff.new(f, t).divmod(unit)
      res.merge(unit => span)
    }.then { |res|
      next res if zeroes

      res.drop_while { |_, v| v.zero? }.to_h
    }
end