Sha256: 4fe47060dacb8d754b72630fd41edaf8e9af020c7132368010ed0adb216554e9

Contents?: true

Size: 1.64 KB

Versions: 1

Compression:

Stored size: 1.64 KB

Contents

module Moments
  class Difference
    def initialize(from, to)
      @from = from
      @to   = to

      if past?
        message = "Start date (#{from}) must be less or equal than the end date (#{@to})."
        raise ArgumentError.new(message)
      end

      precise_difference
    end

    def to_hash
      @diff
    end

    def future?
      @from < @to
    end

    def same?
      @from == @to
    end

    def past?
      @from > @to
    end

    def precise_difference
      @diff = {
        seconds: @to.sec - @from.sec,
        minutes: @to.min - @from.min,
        hours: @to.hour - @from.hour,
        days: @to.day - @from.day,
        months: @to.month - @from.month,
        years: @to.year - @from.year,
      }

      calculate :seconds, :minutes
      calculate :minutes, :hours
      calculate :hours, :days, 24
      calculate_days
      calculate :months, :years, 12

      @diff
    end

    private :precise_difference

    def calculate(attr, subtr, increment = 60)
      if @diff[attr] < 0
        @diff[attr] += increment
        @diff[subtr] -= 1
      end
    end

    private :calculate

    def calculate_days
      if @diff[:days] < 0
        previous_month_days = (Time.new(@to.year, @to.month, 1) - 1).day
        @diff[:days] = precise_previous_month_days(@diff[:days], previous_month_days, @from.day)
        @diff[:months] -= 1
      end
    end

    private :calculate_days

    def precise_previous_month_days(days, previous, from)
      if previous < from
        days = previous + days + (from - previous)
      else
        days = previous + days
      end

      days
    end

    private :precise_previous_month_days
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
moments-0.0.2.alpha lib/moments/difference.rb