Module: Rex::ExtTime

Defined in:
lib/rex/time.rb

Overview

Extended time related functions.

Class Method Summary collapse

Class Method Details

.sec_to_s(seconds) ⇒ Object

Convert seconds to a string that is broken down into years, days, hours, minutes, and second.


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rex/time.rb', line 15

def self.sec_to_s(seconds)
  parts = [ 31536000, 86400, 3600, 60, 1 ].map { |d|
    if ((c = seconds / d) > 0)
      seconds -= c.truncate * d
      c.truncate
    else
      0
    end
  }.reverse

  str = ''

  [ "sec", "min", "hour", "day", "year" ].each_with_index { |name, idx|
    next if (!parts[idx] or parts[idx] == 0)

    str = "#{parts[idx]} #{name + ((parts[idx] != 1) ? 's' :'')} " + str
  }

  str.empty? ? "0 secs" : str.strip
end

.str_to_sec(str) ⇒ Object

Converts a string in the form n years g days x hours y mins z secs.


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rex/time.rb', line 39

def self.str_to_sec(str)
  fields = str.split(/ /)
  secs   = 0

  fields.each_with_index { |f, idx|
    val = 0
    case f
      when /^year/
        val = 31536000
      when /^day/
        val = 86400
      when /^hour/
        val = 3600
      when /^min/
        val = 60
      when /^sec/
        val = 1
    end

    secs += val * fields[idx-1].to_i
  }

  secs
end